C++11 – Understanding Declaration Point for auto Keyword

c++c++11

I had a Q&A before: Point of declaration in C++. The rule point-of-declaration nicely is applicable on many situations. Now, I confused on usage of auto in combination of this rule.

Consider these two codes:

i. Declaring x by itself (we don't expect it to work):

{
  auto x = x;
}

ii. Declaring the inner x by the outer x (It makes error in gcc 4.8.x):

{
  int x = 101; // the outer x
  {
    auto x = x; // the inner x
  }
}

According to the rule of point-of-declaration, it should work but it doesn't. It seems there is another rule in the standard that I missed it. The question is, Where is the point-of-declaration when using auto?

 

There are two possibilities:

i. If the point of declaration is after =, at the end of statement:

auto object = expression;
                        ^
                        Is it here? If it is, why gcc complains?

So the second declaration is valid and must work, because there is no x but that outer one (which is declared before). Therefore auto x=x is valid and the inner x should be assigned to 101.

 

ii. If the point of declaration is before = :

auto object = expression;
           ^

Well, it doesn't make any sense because auto has to wait until see the following expression. For example auto x; is invalid.


Update: I need an answer which explains it by the rule point of declaration.

Best Answer

auto x = x; // inner x

is ill-formed.

To quote from the C++11 standard (emphasis mine):

7.1.6.4 auto specifier

...

3 Otherwise, the type of the variable is deduced from its initializer. The name of the variable being declared shall not appear in the initializer expression. ...

And so because x after = resolves to the x in auto x (as explained in the question you linked), that above piece of code is ill-formed.