Search code examples
c++cfloating-pointundefined-behaviorfloating-point-conversion

Casting double to integer when is it undefined behaviour


So following:

double t = 244.233;
int a = (int) t;

is not undefined behaviour since 244 can fit inside int did I get it right? Otherwise if it was larger value instead of 244 which didn't fit inside int this would be undefined, did I get it right?

I am more interested in how C does this. But is there difference in this case w.r.t to C++?


Solution

  • From [conv.fpint]:

    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.

    So, for example, converting 66666.66 to an int16_t would be undefined behavior, but converting 66.66 is just fine.