Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++11

auto

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'

like image 907
A-n-t-h-o-n-y Avatar asked Oct 19 '25 01:10

A-n-t-h-o-n-y


1 Answers

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);
like image 148
R Sahu Avatar answered Oct 21 '25 13:10

R Sahu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!