C++ – What happens in C++ when an integer type is cast to a floating point type or vice-versa

ccastingfloating pointperformance

Do the underlying bits just get "reinterpreted" as a floating point value? Or is there a run-time conversion to produce the nearest floating point value?

Is endianness a factor on any platforms (i.e., endianness of floats differs from ints)?

How do different width types behave (e.g., int to float vs. int to double)?

What does the language standard guarantee about the safety of such casts/conversions? By cast, I mean a static_cast or C-style cast.

What about the inverse float to int conversion (or double to int)? If a float holds a small magnitude value (e.g., 2), does the bit pattern have the same meaning when interpreted as an int?

Best Answer

Do the underlying bits just get "reinterpreted" as a floating point value?

No, the value is converted according to the rules in the standard.

is there a run-time conversion to produce the nearest floating point value?

Yes there's a run-time conversion.

For floating point -> integer, the value is truncated, provided that the source value is in range of the integer type. If it is not, behaviour is undefined. At least I think that it's the source value, not the result, that matters. I'd have to look it up to be sure. The boundary case if the target type is char, say, would be CHAR_MAX + 0.5. I think it's undefined to cast that to char, but as I say I'm not certain.

For integer -> floating point, the result is the exact same value if possible, or else is one of the two floating point values either side of the integer value. Not necessarily the nearer of the two.

Is endianness a factor on any platforms (i.e., endianness of floats differs from ints)?

No, never. The conversions are defined in terms of values, not storage representations.

How do different width types behave (e.g., int to float vs. int to double)?

All that matters is the ranges and precisions of the types. Assuming 32 bit ints and IEEE 32 bit floats, it's possible for an int->float conversion to be imprecise. Assuming also 64 bit IEEE doubles, it is not possible for an int->double conversion to be imprecise, because all int values can be exactly represented as a double.

What does the language standard guarantee about the safety of such casts/conversions? By cast, I mean a static_cast or C-style cast.

As indicated above, it's safe except in the case where a floating point value is converted to an integer type, and the value is outside the range of the destination type.

If a float holds a small magnitude value (e.g., 2), does the bit pattern have the same meaning when interpreted as an int?

No, it does not. The IEEE 32 bit representation of 2 is 0x40000000.

Related Topic