Variable i
is becoming 8
at the first entry in loop. Then how the condition i <= 2
satisfied next time?
#include <stdio.h>
int main()
{
int i;
for (i = 0; i <= 2; i++)
{
int i = 8;
printf("%d", i);
}
printf("%d", i);
return 0;
}
int i=8
is a declaration of a new variable (declares and initializes new variable) which is in a local scope that shadows the existing variable from the more general scope.
In other words:
int i
defines variable;for
uses that variable and initializes it with 0
and starts a cycle;int i=8
- as it is written with int
- defines new local variable that because it has the same name that i
from outer scope - shadows it ("shadowing" is a term). And so further code in the loop uses new local i
which set to 8
.printf("%d",i);
prints 8
.i=8
erased also.for
lives outside (in more general scope) of the scope of the loop. for
condition uses variable from outside, which was set to i=0
in step #2. So for
in a second cycle instructed to increment (i++
) it, so i=1
, which passes the i <= 2
check. So for
indeed starts executing next cycle of internal code.for
loop external i
gets shadowed by internal int i=8
... (step #3).In short: It is because code declares a new variable with int i
.
The good style is to:
for(int i=0;i<=2;i++)
- always declare and initialize the variable in one instruction.