What I have known so far is, multiple declarations inside a block produce an error message and also uninitialized local variable gives garbage value on printing.
But
A block is anything in curly braces. A block doesn't have to follow a for
do
, while
, if
, etc. Literally any set of statements can be enclosed in their own block scope using curly braces.
The i
in the for
loop is not in the loop body scope since it is outside the curly braces. The i
in the block is indeed uninitialized and contains garbage. Garbage usually just means "whatever was there before". As often as not, that value will be zero. That doesn't make it any less garbage.
The scope of a variable declared in the first part of the for
loop is all three parts of the for
plus the loop body. In your case the body of the loop is a compound statement, and you declare another variable named i
in that block, so it masks the i
declared in the for
.
So in your piece of code there are three relevant scopes:
main
functionfor
loop.for
loop.And each of them is "internal" to the other, so a variable declared at one of these scopes masks a variable of the same name in a higher scope.
To further illustrate this, if we modify your code as follows:
int main()
{
int i = 9;
printf("outer i: %d\n", i);
for(int i = 5;i>0;printf("middle i:%d\n", i),i--){
int i = 7;
printf("inner i: %d\n",i);
}
printf("outer i: %d\n", i);
}
The output is:
outer i: 9
inner i: 7
middle i:5
inner i: 7
middle i:4
inner i: 7
middle i:3
inner i: 7
middle i:2
inner i: 7
middle i:1
outer i: 9
As for why your code is printing 0 inside of the loop, an uninitialized variable may have any value, including 0. So just because it's printing 0 doesn't mean it's not garbage.