What precedence are types derived when using auto?

95 Views Asked by At

I'd like to know in what order are types derived when using auto in C++? For example if I have

auto x = 12.5;

Will that result in a float or a double? Is there any reason it chooses one over the other in terms of speed,efficiency or size? And in what order are the types derived? Does it try int then double then string or is it not that simple?

Thanks

1

There are 1 best solutions below

4
On BEST ANSWER

While C++ allows initialization of different typed variables with the same kind of literal, all literals in C++ have one specific type. Therefore the type deduction for auto variables does not need to be special for initialization with literals, it just takes the type of the right hand side (the single, unambiguous type of the literal, in your case) and applies it to the variable. Examples for literals and their different types:

12.5   //double
12.5f  //float
13     //int
13u    //unsigned int
13l    //long
13ull  //unsigned long long
"foo"  //char const [4]
'f'    //char

So what about float f = 12.5;? Very simple: here the float f is initialized with a literal of type double and an implicit conversion takes place. 12.5 for itself never is float, it always is double.

An exception where the type of the auto variable does not have the type of the literal is when array-to-pointer decay takes place, which is the case for all string literals:

auto c = "bar"; //c has type char const*, while "bar" has type char const[4]

But this again is not special for literals but holds for all kinds of arrays:

int iarr[5] = {};
auto x = iarr; //x has type int*