Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
183 views
in Technique[技术] by (71.8m points)

c++ - Error redeclaring a for loop variable within the loop

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:

1010101010

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...