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.
Syntax. The for loop consists of three optional expressions, followed by a code block: initialization - This expression runs before the execution of the first loop, and is usually used to create a counter. condition - This expression is checked each time before the loop runs.
In computer programming, a loop variable is a variable that is set in order to execute some iterations of a "for" loop or other live structure.
In C/C++, the scope of a variable declared in a for or while loop (or any other bracketed block, for that matter) is from the open bracket to the close bracket.
C/C++ use lexical scoping. The lifetime of a variable or object is the time period in which the variable/object has valid memory. Lifetime is also called "allocation method" or "storage duration."
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With