Search code examples
c++c++11auto

`auto` variable declaration with multi-word fundamental types causes error


Is it possible to declare a variable with the auto keyword and a type name that is made of two or more words?

And if not, why not?

For example

auto foo = unsigned int{0};

Give the following compiler output

Clang:

error: expected '(' for function-style cast or type construction

GCC:

error: expected primary-expression before 'unsigned'


Solution

  • For

    auto foo = T{0};
    

    to work, T has to be a simple-type-specifier.

    From the C++11 Standard/5.2.3 Explicit type conversion (functional notation)/3

    Similarly, a simple-type-specifier or typename-specifier followed by a braced-init-list creates a temporary object of the specified type direct-list-initialized ([dcl.init.list]) with the specified braced-init-list, and its value is that temporary object as a prvalue.

    If you see the definition of simple-type-specifier, unsigned int is not one of them.

    You can use any of the following:

    auto foo = 0U;
    auto foo = (unsigned int)0;
    auto foo = static_cast<unsigned int>(0);