Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 217
J. Doe Avatar asked Jan 04 '23 02:01

J. Doe


1 Answers

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
}
like image 131
Vittorio Romeo Avatar answered Jan 05 '23 14:01

Vittorio Romeo