Reputation: 669
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 double
type before the addition of 3.541.
The question stems from the fact that for most integral types, they are mostly promoted to int
during implicit conversion unless they are unable to fit into int
. Since int
and float
both the same size of 4 bytes, and that 3.0 and 3.541 can perfectly fit into a float
, why is the higher order double
used for implicit conversion in this case as opposed to float
? Does this mean that for any integral type to floating point type implicit conversion, the integral type will be converted to a double
regardless of the precision or size?
Thanks a bunch!
Upvotes: 0
Views: 1538
Reputation: 11807
By default if you write something like:
int ival = 3.541 + 3;
3.541
will be considered a double
, because without any suffix, that is what is assumed by the compiler by default. If you wanted it to be treated like a float, do this:
int ival = 3.541f + 3; //See the 'f' there. For floats
Also, if you are wondering why sometimes 3.1541
is not represented properly is probably because its binary representation isn't accurate enough. Read this article for more info
Upvotes: 1
Reputation: 31260
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 http://en.cppreference.com/w/cpp/language/floating_literal .
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).
Upvotes: 5