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 coming across an example of for
loop in C has shaken my concept on the scope of variables.
Below is the code for the same:
#include<stdio.h>
int main()
{
int i;
for(int i = 5; i > 0 ; i--){
int i;
printf("%d ", i);
}
}
The above code produces the output
0 0 0 0 0
I have two questions
A
for
loop is considered as one block then how two different memories are allocated for two declarations of same variablei
? And if the first line of for loop and its body are considered as two blocks, then how to identify different block?Inside the body of the loop, the variable
i
is uninitialized, then how is it taking the value as 0, as it should be having garbage value?
Please, explain this.