{
int i;
for(i=0;i<5;i++)
{
int i=10;
printf("%d",i);
}
}
I have two questions
- Why is there no redeclaration error for
i
? - why output will be
10
5 times and not10
1 time?
{
int i;
for(i=0;i<5;i++)
{
int i=10;
printf("%d",i);
}
}
I have two questions
i
?10
5 times and not 10
1 time?
If you ask your compiler nicely (
gcc -Wshadow
) it will warn youIn your code
int i;
is in outer block scope.int i=10;
is in the inner block scope for thefor
loopIf we visualize the same, we can come up with something like'
The case here is, the inner
i
will shadow the outeri
. These two are considered seperate variable (based on their scope).In other words, the
i
which is defined and present inside the block (inner scope) will have more preference (over the variable in outer scope). So, the inneri
value will get printed.OTOH, the loop counter variable
i
remains at the outer scope. It's value is not altered through the assignement inside the block. So, rightly it loops for 5 times, as asked.Related: From
C11
standard, chapter §6.2.1, paragraph 4,So, to answer your questions,
Because two
i
s are treated as seperate variable, despite being named same.Because, the outer
i
, used as the counter, is not changed from inside the loop, only the loop increment condition is altering that value.You aren't re-declaring i since the second declaration of i ( 'int i =10' ) is inside a loop . That's means that in your example the variable is destroyed and recreated for each iteration of the loop .
The scope of variables created in any compound statement is limited to the compound statement itself .
Ps : If you wanted to stop the loop by changing the value of i
It all has to do with the scope of an identifier. An identifier is simply a name given to an entity (object, function, typedef name and so on) in C and, as per
C11 6.2.1 /1
:The scope of an entity is described in
/2
of that section:And
/4
covers your specific case:In other words, something like:
is perfectly valid, and will print
42 17 42
. That's because the identifieri
inside the inner block is in its own scope, which ends at the first closing brace.In your particular case, you can think of it as:
The inner
int i=10
effective hides the outeri
for the duration of the body of thefor
loop. That's why it prints a lot of10
s rather than0..4
.The scope of the inner
i
finishes at the closing brace of thefor
loop body so that, when the continuation condition of thefor
loop is checked, it once again sees the outeri
. That's why it loops five times rather than once.