Casting double to integer when is it undefined behaviour

1.8k views Asked by At

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++?

3

There are 3 answers

1
Barry On BEST ANSWER

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.

0
Baum mit Augen On

From my favorite documentation:

A prvalue of floating-point type can be converted to prvalue of any integer type. The fractional part is truncated, that is, the fractional part is discarded. If the value can not fit into the destination type, the behavior is undefined (even when the destination type is unsigned, modulo arithmetic does not apply).

So yes, you are right. (For C++, but someone already posted a near identical standard quote for C)

0
ouah On

Undefined behavior in C if the integral part cannot be represented in the integer type.

(C11, 6.3.1.4p1) "When a finite value of real floating type is converted to an integer type other than _Bool, the fractional part is discarded (i.e., the value is truncated toward zero). If the value of the integral part cannot be represented by the integer type, the behavior is undefined.61"

Similar wording in C++ in C++11, 4.9p1.