I have compiled following program using  gcc prog.c -Wall -Wextra -std=gnu11 -pedantic command on GCC compiler. I wondered, it is working fine without any warnings or errors. 
#include <stdio.h>
int main(void)
{
    for (int i = 0; i == 0;  i++) 
    {        
        printf("%d\n", i);
        long int i = 1; // Why doesn't redeclaration error?
        printf("%ld\n", i);
    }
}
Why compiler doesn't generate redeclaration variable i error?
From standard §6.8.5.5 (N1570)
An iteration statement is a block whose scope is a strict subset of the scope of its enclosing block. The loop body is also a block whose scope is a strict subset of the scope of the iteration statement.
Emphasis added
In C language, the scope of statement is nested within the scope of for loop init-statement.
According to Cppreference :
While in C++, the scope of the init-statement and the scope of statement are one and the same, in C the scope of
statementis nested within the scope ofinit-statement.
According to stmt:
The for statement
for ( for-init-statement conditionopt ; expressionopt ) statementis equivalent to
{ for-init-statement while ( condition ) { statement expression ; } }except that names declared in the for-init-statement are in the same declarative-region as those declared in the condition, and except that a continue in statement (not enclosed in another iteration statement) will execute expression before re-evaluating condition.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With