Search code examples
c++c++11typesauto

Confusion about 'auto' deduction type


int i = 0;

is equivalent to

int i;
i = 0;

Then,

auto i = 0;

It's OK, working fine. But,

auto i;
i = 0;

compiler gives an error.

So, Why compiler gives an error?


Solution

  • It's not equivalent because auto is not a type. In both examples, i type is int. auto means that variable type is determined by type of expression it is initialized with (int this case, it's int, as that's the type of literal 0). That is,

    auto i = 0;
    

    is equivalent to:

    int i = 0;
    

    The snippet

    auto i;
    i = 0;
    

    does not make sense, because there's no expression that compiler can deduce type from.

    One could argue that compiler could look further to deduce type, but that would be extra effort for little value, so it's unlikely to make way into future C++ standards. And what type would be inferred in the following example:

    auto i;
    if (...)
        i = 0;
    else
        i = "WAT?";
    

    BTW, int i = 0; is equivalent to int i; i = 0 but is not the same. First is initialization, second is default initialization followed by assignment. For types other than int, namely classes with non-trivial constructors and/or assignment operators, the two snippets may not be equivalent.