Why compiler doesn't generate redeclaration variable i error?
From C Standards#6.2.1p4 Scopes of identifiers
Every other identifier has scope determined by the placement of its declaration (in a declarator or type specifier). If the declarator or type specifier that declares the identifier appears outside of any block or list of parameters, the identifier has file scope, which terminates at the end of the translation unit. If the declarator or type specifier that declares the identifier appears inside a block or within the list of parameter declarations in a function definition, the identifier has block scope, which terminates at the end of the associated block. If the declarator or type specifier that declares the identifier appears within the list of parameter declarations in a function prototype (not part of a function definition), the identifier has function prototype scope, which terminates at the end of the function declarator. If an identifier designates two different entities in the same name space, the scopes might overlap. If so, the scope of one entity (the inner scope) will end strictly before the scope of the other entity (the outer scope). Within the inner scope, the identifier designates the entity declared in the inner scope; the entity declared in the outer scope is hidden (and not visible) within the inner scope.
From C standards#6.8.5p5 Iteration statements
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.
So, in this code:
for (int i = 0; i == 0; i++)
{
printf("%d\n", i);
long int i = 1; // Why doesn't redeclaration error?
printf("%ld\n", i);
}
the scope of identifier with name i
is overlapping and in this name space, the i
declared in for (int i = 0; i == 0; i++)
has outer scope and the one declared within loop body long int i = 1;
has inner scope.
Within the loop body, after this statement:
long int i = 1;
the i
declared in the outer scope is not visible and printf()
printing the value of i
visible in the inner scope which is 1
.
This behavior is also known as Variable Shadowing which occurs when a variable declared within a certain scope has the same name as a variable declared in an outer scope.
C language allows variable shadowing and that's why the compiler does not throw any error for this. However, in gcc
compiler, if you use -Wshadow
option you will get a warning message - declaration shadows a local variable
.