Multiple declarations are the same for variables inside and outside the 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 declared outside the for loop, and it is again declared and initialized inside the for loop. How does C allow multiple declarations?

+5
source share
3 answers

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

  • External i will work throughout main .

  • Inner i will only work for one iteration of the loop.

The inner shadow is external in this area:

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

Due to shadow copy rules, it is not possible to refer to an external one while inside the aforementioned area.


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

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

Variables in one area can mask variables in a higher area.

In this example, i defined inside the loop masks i defined outside. In the body of the loop, printf prints the value of internal i , which is 10. Then i++ runs again on internal i , setting it to 11.

When the loop goes to the bottom and comes back, the inner i goes beyond. Then the second and third for clauses act on the outer i . When the body of the loop is reintroduced, a new instance of internal i is defined and initialized to 10.

+3
source

You should check the following page for definitions of the different types of areas that C variables can have.

http://aelinik.free.fr/c/ch14.htm

Your first int i is in the scope of the whole block, and the second int i has scope within this nested loop. After the external nested loop, source code version i is applied again.

+1
source

Source: https://habr.com/ru/post/1274079/


All Articles