Whenever you create a local variable to a function, it is allocated to a memory area called "the stack". It contains the local variables and some more information that allows the computer to know, when a function finishes being executed, to which point of the previous function it has to return, and so on, until it reaches the main()
.
One feature of this stack is that if a function is invoked, it uses part of that memory to store its local functions. After this function returns, the memory it used is released, and if later the code that called this function calls another, it uses the same memory space as the first function used to store the local variables of the second. Besides, she doesn’t care about zeroing out that memory region even after allocating space, or before releasing it again.
The result of all this is that the value you find in an uninitialized local variable will depend on which functions previously ran in that program and how they finished executing them. In other words, and by borrowing the terminology from the C standard, when you read the value of an uninitialized local variable, the behavior is undefined. That is, any value can be there. In your case, it happened to be one; it could be -1,357,928, too.
What is the lesson learned? Always initialize your local variables when declaring them. You’ll save yourself trouble sooner or later.
It is possibly a question of the compiler initializing its variables. Since you did not set the value they start, it may be that the variable started with value 1. I tested on Repl.it and resulted in 100, but Ideone resulted in 150505460. That is, if you do not initialize the variable, the behavior cannot be predicted.
– Woss
Thanks for the answer too, and for having tested, you also showed me that I always need to initialize local variables.
– Monteiro