Search code examples
c++castingstandardsnarrowing

What guarantees does the C++ standard give for narrowing conversion from double to int?


What guarantees does the C++ standard give for narrowing conversion from double to int types? Is it the same as Java as explained at Q31328190:


Solution

  • No, it's not the same as in Java. If the mathematical result of "truncate the fractional part" cannot be represented by the target type, the behaviour is undefined.

    From 4.9 [conv.fpint]/1 ("Floating-integral conversions"):

    A prvalue of a floating point type can be converted to a prvalue of an integer type. The conversion truncates; that is, the fractional part is discarded. The behavior is undefined if the truncated value cannot be represented in the destination type.