简体   繁体   中英

Why doesn't the C++11 compiler complain when I initialize a local variable with the same name multiple times within the same scope?

So if I initialize a variable of the same type and name within the main function the compiler will complain of the re declaration, for example:

for (int i = 0; i < 5; i++)
{
    int a{5};
    int a{5}; // error int a previously declared here
}

But there are no errors if I compile this instead:

for (int i = 0; i < 5; i++)
{
    int a{5};
}

To my understanding, this looks as if I have initialized "int a" multiple times within the same scope which obviously would cause an error. If somebody could explain what's actually happening it would be greatly appreciated! Thanks!

You are confusing scope and lifetime, it seems.

 for (int i = 0; i < 5; i++) { int a{5}; } 

To my understanding, this looks as if I have initialized "int a" multiple times within the same scope which obviously would cause an error.

Why would that obviously cause an error? a is always the same variable , in every iteration of the loop. But it always points to a different object , whose lifetime begins and ends with the current iteration.

If such a thing would not work, then you could not even call the same function two times:

void f()
{
    int x = 0;
}

f();
f(); // why should this be an error?

Note that this question goes far beyond g++, and even far beyond C++. Every C-derived programming language works exactly like that. At least I've never seen one which doesn't.

To my understanding, this looks as if I have initialized "int a" multiple times within the same scope

You are right about the "multiple times" part, but you are wrong about "same scope": the scope of the second int a is nested inside the outer scope, in which the first int a is declared. Hence, the second declaration is legal: it hides the outer declaration, which the language allows.

int a = 5;
cout << a << endl;
{
    int a = 6;
    cout << a << endl;
}
cout << a << endl;

Demo above produces this output:

5
6
5

I think your getting confused with declaring variable and initializing it

for (int i = 0; i < 5; i++)
{
    int a{5}; // In this part you are declaring and initializing the variable
    int a{5}; // error int a previously declared here
    // same with this case as well
}

If you want to do that you can use this

 for (int i = 0; i < 5; i++)
    {
         int a{5}; 
         a=5; // error int a previously declared here

     }

at this point int a{5} This will be the declaration of a variable and initialization of variable in the for loop scope

and a=5; and here reinitialize that particular variable in the same scope

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM