TruthOrDare TruthOrDare - 3 months ago 9
C++ Question

Why is int promoted to double and not float for implicit conversion

I'm currently learning C++ thought C++ Primer. In chapter 4.11 on Type Conversion, I noticed that the chapter rarely talks about the implicit conversion from integral to floating point types, but really focused mostly on conversion within the integral types. Thus, I am not really sure about the rules of conversion from integral type to floating point type.

My question is from the chapter's example:

int ival = 3.541 + 3

The chapter mentioned that 3 is converted to a
type before the addition of 3.541.

The question stems from the fact that for most integral types, they are mostly promoted to
during implicit conversion unless they are unable to fit into
. Since
both the same size of 4 bytes, and that 3.0 and 3.541 can perfectly fit into a
, why is the higher order
used for implicit conversion in this case as opposed to
? Does this mean that for any integral type to floating point type implicit conversion, the integral type will be converted to a
regardless of the precision or size?

Thanks a bunch!


3.541 is a double. So that's what the other argument needs to be converted to.

Suffixes are used to denote the precision of a literal, 3.541f (or F) would be a float, 3.541L (or l) would be a long double. The default (no suffix) is double. Source .

3.541 does not fit into any of those lengths, as it's a repeating fraction in binary. The real value will be the floating point value as close to 3.541 as possible (like 3.540999999999999925393012745189480483531951904296875 in case of a double).