Search code examples
c++auto

Implicit pointer variable with another in auto definition


Why is it not possible to define an implicit type modifier * (pointer) together with another variable of the same base type?

int i = 1;
auto ip = &i;   // fine
auto *ip2 = &i; // fine

// error: inconsistent deduction for ‘auto’: ‘int*’ and then ‘int’
// auto ip3 = &i, ir = i; 
// auto ip4 = &i, ival = i;

auto *ip5 = &i, &ir2 = i;   // fine
auto *ip6 = &i, &ival2 = i; // fine

I generally prefer more explicit code and usage of * and & to increase readability and intentions. Here I would even define one variable per line. But in this case I wonder why the implicit usage of a different type modifier for the base type doesn't work in case of ip3 and ip4.

Is that a safety measure or a constraint?


Solution

  • There is no such thing as a "base type" in the context in which you're trying to use it; int* is a different type from int, period.

    auto must "resolve" to the same type in the whole multi-variable declaration, otherwise it's often ambiguous as to which one you wanted (think about conversions).