Why does auto deduce this variable as double and not float?
Type of literal 3.5
is double
. For float
please use 3.5f
You can play with this snippet to see various type information.
3.5
is a double
literal. Thus auto
correctly deduces its type as double
. You can still use it to initialize a float
variable, but the most correct way is to use a float
literal like 3.5f
. The f
at the end is called a suffix. Suffixes for floating point literals are:
- (no suffix) defines double
f
F
defines floatl
L
defines long double
Besides floating point literals, there are also suffixes for integral literals and user-defined literals.
In C++ (and C), floating literals are treated as double
by default unless specified by f or F or l or L
.
The standard has following:
2.14.4 The type of a floating literal is double unless explicitly specified by a suffix. The suffixes f and F specify float, the suffixes l and L specify long double. If the scaled value is not in the range of representable values for its type, the program is ill-formed.
Hence,
auto one = 3.5;
is always double
and if you intend float
it should be coded as
auto one = 3.5f;