Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Re-declaring variable inside for loop in C

Tags:

c

gcc

declaration

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?

like image 976
msc Avatar asked Nov 30 '17 05:11

msc


2 Answers

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

like image 147
user2736738 Avatar answered Oct 05 '22 22:10

user2736738


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 statement is nested within the scope of init-statement.

According to stmt:

The for statement

for ( for-init-statement conditionopt ; expressionopt ) statement

is 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.

like image 28
msc Avatar answered Oct 05 '22 22:10

msc