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
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:So what about
float f = 12.5;
? Very simple: here thefloat f
is initialized with a literal of typedouble
and an implicit conversion takes place.12.5
for itself never isfloat
, it always isdouble
.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:But this again is not special for literals but holds for all kinds of arrays: