问题
In c, when this block of code is run,it outputs 10 10 10 10 10. I think the loop should exit after 1st execution as i becomes 11 but it is not happening. Why it is so?
#include<stdio.h>
int main()
{
int i;
for(i=0;i<5;i++)
{
int i=10;
printf("%d\t",i);
i++;
}
return;
}
But when program is written as below the output is similar to what i am thinking(i.e.10 ).What is the exact difference between above code and the code shown below? How C is handling these variable? I would be glad if anyone explain about this.
#include<stdio.h>
int main()
{
int i;
for(i=0;i<5;i++)
{
i=10;
printf("%d\t",i);
i++;
}
return;
}
回答1:
In your first program, for
loop is using the i
declared outside the for
to control the loop. The printf
uses the i
declared inside the for
loop to print the value and this i
has block scope.
The new declaration of i
in the for loop
temporarily hides the old declaration. Now the value of i
is 10
. At the end of the for
loop block the new i
is not visible to the program and the variable regains its old meaning and this time i
stores the value as per the iteration of loop (either 1
, 2
, 3
or 4
).
回答2:
In the first code you declare your variable twice: one outside the loop and the second one inside the loop. So inside the loop compiler found another declaration for the variable so it uses the inner declaration (this called block scope).
So that the first program print 10 10 10 10 10
because this is the inner declaration int i=10
But in the second code you declare it once so the compiler use this declaration in the whole program.
回答3:
In C99 or later, you can write this variation on your code with 3 independent variables called i
:
#include <stdio.h>
int main(void)
{
int i = 19;
printf("i0 = %d\n", i);
for (int i = 0; i < 5; i++)
{
printf("i1 = %d\n", i);
int i = 10;
printf("i2 = %d\n", i);
i++;
}
printf("i0 = %d\n", i);
return 0;
}
The output is:
i0 = 19
i1 = 0
i2 = 10
i1 = 1
i2 = 10
i1 = 2
i2 = 10
i1 = 3
i2 = 10
i1 = 4
i2 = 10
i0 = 19
(In C89, you can't have the variable tagged i1
in the output, and you couldn't demonstrate the two variables in the loop because declarations have to precede statements such as printf()
calls.)
回答4:
Because in first example the i
inside the loop is not the same as the one which governs/controls the loop, it is a completely different variable though with same name.
来源:https://stackoverflow.com/questions/20815771/variable-scope-in-c-programming