Search code examples
c++c++11auto

What happens when one uses auto with two declarations in C++11?


Let's say there is a loop like this:

for(size_t i=0, n=ar.size(); i<n; ++i)
{
  // ...
}

Would it be good to rewrite it as:

for(auto i=0, n=ar.size(); i<n; ++i)
{
  // ...
}

In other words will the two variables i and n always end up being the same datatype.

When i try something like this:

auto i=0, s="";

g++ 4.8.4 generates an error inconsistent deduction for ‘auto’: ‘int’ and then ‘const char*’. But i cannot find out if it's just g++ or this is actually required according to the standard to use every value in the type deduction.


Solution

  • This is [dcl.spec.auto, 7.1.6.4]/8:

    If the init-declarator-list contains more than one init-declarator, they shall all form declarations of variables. The type of each declared variable is determined as described above, and if the type that replaces the placeholder type is not the same in each deduction, the program is ill-formed.

    That is, all deduced types have to be the same.

    There's even an example in the same paragraph:

    auto x = 5, *y = &x;       // OK: auto is int
    auto a = 5, b = { 1, 2 };  // error: different types for auto