Search code examples
cvariable-declaration

Multiple declarations same of variables inside and outside for loop


#include <stdio.h>
int main()
{
    int i;
    for ( i=0; i<5; i++ )
    {
        int i = 10;
        printf ( "%d", i );
        i++;
    }
return 0;
}

In this variable i is declared outside the for loop and it is again declared and initialized inside for loop. How does C allows multiple declarations?


Solution

  • The i outside the loop and the i inside the loop are two different variables.

    • The outer i will live for the entire duration of main.

    • The inner i will only live for the duration of one loop iteration.

    The inner one shadows the outer one in this scope:

    {
        int i = 10;
        printf ( "%d", i );
        i++;
    }
    

    Due to shadowing rules, it is impossible to refer to the outer one while inside the aforementioned scope.


    Note that it is impossible to declare two variables with the same name in the same scope:

    {
        int i = 0;
        int i = 1; // compile-time error
    }