Let’s look at the following piece of code which I unintentionally wrote:
void test (){
for (int i = 1; i <=5; ++i){
float newNum;
newNum +=i;
cout << newNum << " ";
}
}
Now, this is what I happened in my head:
I have always been thinking that float newNum would create a new variable newNum with a brand-new value for each iteration since the line is put inside the loop. And since float newNum doesn’t throw a compile error, C++ must be assigning some default value (huhm, must be 0). I then expected the output to be “1 2 3 4 5”. What was printed was “1 3 6 10 15”.
Please help me know what’s wrong with my expectation that float newNum would create a new variable for each iteration?
Btw, in Java, this piece of code won’t compile due to newNum not initialized and that’s probably better for me since I would know I need to set it to 0 to get the expected output.
Since
newNumis not initialized explicitly, it will have a random value (determined by the garbage data contained in the memory block it is allocated to), at least on the first iteration.On subsequent iterations, it may have its earlier values reused (as the compiler may allocate it repeatedly to the same memory location – this is entirely up to the compiler’s discretion). Judging from the output, this is what actually happened here: in the first iteration
newNumhad the value 0 (by pure chance), then 1, 3, 6 and 10, respectively.So to get the desired output, initialize the variable explicitly inside the loop: