Reputation: 149
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 3; j++)
{
int n;
n++;
printf("n : %d\n", n)'
}
}
The output of the code is 1 2 3 4 5 6 7 8 9. I'm wondering why the variable n in the for loop isn't initialized when the variable declaration is executed.
Upvotes: 5
Views: 978
Reputation: 6419
You're never initializing n to a specific value. C++ will not do this by default when you call int n
. Instead, it just reserves an integer sized block of memory. So when you call n++
, the program is just grabbing whatever value happens to be in that memory and incrementing it. Since you're doing this in quick succession and not creating new variables in between, it happens to be grabbing the same memory over and over. As @NicolasBuquet points out, compiler optimization may also be responsible for the consistency with which the same chunk of memory is picked.
If you were to assign a value to n, (i.e. int n = 1;
) this behavior would go away because a specific value will be written to the chunk of memory assigned to n.
Upvotes: 13
Reputation: 278
In C++, no variable is initialized with a default value; you must specify one explicitly should you find the need to do so.
The result of your code is really undefined; it is just pure luck that you are getting the numbers 1 through 9 in sequence. On some other machine or implementation of C++, you might get different results.
Upvotes: 1