You are confusing two things, "how for
works" (which isn't your actual problem), and variable scope (which is).
Consider:
#include <stdio.h>
int main()
{
int i = 0;
printf( "Address of i outside the loop: %p\n", &i );
for ( int i = 0; i < 5; ++i ) // this "shadows" i
{
printf( "Address of i inside the loop: %p\n", &i );
}
}
You will see that the i
inside the loop is at a different address. There are two variables named i
here, and inside the for
loop, the one declared at the beginning of the program is not visible.
This has nothing to do with how for
works; it would be the same here:
#include <stdio.h>
int main()
{
int i = 0;
printf( "Address of i outside the block: %p\n", &i );
{
int i = 0; // this "shadows" i
printf( "Address of i inside the block: %p\n", &i );
}
}
You are looking at a "shadowed" variable: Inside the for
loop / code block, i
means something other than outside.
If you write this:
#include <stdio.h>
int main()
{
int i = 0;
printf( "Address of i outside the loop: %p\n", &i );
for ( i = 0; i < 5; ++i ) // does NOT "shadow" i
{
printf( "Address of i inside the loop: %p\n", &i );
}
}
...you don't redeclare i
-- no int
in the for
statement, so there is only one declaration, and only one variable named i
in the program.
for
is not a function or a macro, but a keyword of the language. There is no convenient bit of code that would show you its inner workings, as what it does would be spread out across the various compiling stages (lexing, parsing, code generation). But as I showed above, what confuses you has nothing to do with for
in the first place, but with variable scope. I hope the example snippets help you understanding the issue better.