The code is as follows:
#include <stdio.h>
int main()
{
int i;
printf("%p\n",&i);
for (i = 0; i < 5; i++)
{
int i = 10;
printf("%d %p\n", i,&i);
i++;
}
return 0;
}
First we defined a variable i
(just after main). Then at the start of for
loop we defined the same variable i
again. So, inside for
loop, value of i
is 10. The for
loop must iterate only once, since i>5
after first iteration. But to my surprise the output is as follows:
0x7ffe8b799da0
10 0x7ffe8b799da4
10 0x7ffe8b799da4
10 0x7ffe8b799da4
10 0x7ffe8b799da4
10 0x7ffe8b799da4
My questions are:
1) Why is the compiler considering the initial defined variable i
while executing i<5;i++
instruction and, not the re-defined variable i
? (after first iteration).
2) Why did compiler assign different memory address to same variable identifier i
?
Why is the compiler considering the initial defined variable i while executing i<5;i++ instruction and, not the re-defined variable i? (after first iteration).
Because the re-defined (shadowing) variable isn't in scope yet. If you remove the first definition, you get an "identifier undeclared" error. This also doesn't change after the first iteration of the loop as it is determined at compile time.
2) Why did compiler assign different memory address to same variable identifier i?
Even though you can't access the outer int i
inside the loop as the second one shadows it, it still exists and therefore needs its own memory. It's not overwritten by the other int i
. You can see that by putting a printf("%d\n", i);
after the loop - it will print 5
, because that's the value of that i
after loop.
On another note, the i++;
at the end of the loop has no effect because it affects the i
inside the loop, which goes out of scope right after the i++;
. This is unlike the i++;
in the for (i = 0; i < 5; i++)
, which increases the outer i
.