In the snippet below, auto deduces the variable to double, but I want float.
auto one = 3.5;
Does it always use double for literals with a decimal point? How does it decide between float and double?
In the snippet below, auto deduces the variable to double, but I want float.
auto one = 3.5;
Does it always use double for literals with a decimal point? How does it decide between float and double?
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:
f F defines float l 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;
The type of a floating point literal in C++ is automatically double unless:
f is suffixed, in which case the type of the literal is float
L is suffixed, in which case the type of the literal is long double
So, if you want your variable to be a float, do this:
auto one = 3.5f;