Every variable refers to its most recent declaration (that is valid in that scope of course):
main()
{
int i=3;
while(i--) // this i is the one defined in the line above
{
int i=100;
i--; // this i is the one defined in the line above
printf("%d..",i); // this i is the one defined two lines above
}
}
So your while loop iterates 3 times because it depends on the i
that is declared by int i = 3;
Inside the loop it prints 99
because there i
refers to the i
that is declared by int i = 100;
, which is --
ed.
If you change int i = 100;
to i = 100
, then you are changing the first i
and not introducing another variable. Hence the infinite loop.
Edit Some people said instead of "most recent" I should say "innermost declaration accessible in the current scope" giving this example:
int a=4;
{
int a=10;
}
printf("%d", a);
Since the second a
is not visible by printf
, obviously printf("%d", a);
cannot refer to it. I assumed the reader knows enough to know a variable is accessible only inside the scope it is defined in. Otherwise, yes the phrases in the first two comments are more precise.