Why getting redeclaration error of variable in a for loop in this code?

  • A+

Consider this snippet of a C program:

for(int i = 0; i < 5; i++) {     int i = 10;  // <- Note the local variable      printf("%d", i);  }     

It compiles without any error and, when executed, it gives the following output


But if I write a similar loop in C++

for(int i = 0; i < 5; i++) {      int i = 10;       std::cout << i;  } 

The compilation fails with this error

prog.cc:7:13: error: redeclaration of 'int i'        int i = 10;            ^   prog.cc:5:13: note: 'int i' previously declared here        for(int i = 0; i < 5; i++)                ^    

Why is this happening?

This is because C and C++ languages have different rules about re-declaring variables in a scope nested in a for loop:

  • C++ puts i in the scope of loop's body, so the second int i = 10 is a redeclaration, which is prohibited
  • C allows redeclaration in a scope within a for loop; innermost variable "wins"

Here is a demo of a running C program, and a C++ program failing to compile.

Opening a nested scope inside the body fixes the compile error (demo):

for (int i =0 ; i != 5 ; i++) {     {         int i = 10;         cout << i << endl;     } } 

Now i in the for header and int i = 10 are in different scopes, so the program is allowed to run.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: