3

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

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847

3 Answers3

8

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.

Barry
  • 286,269
  • 29
  • 621
  • 977
  • 1
    For the record, "cannot be represented" includes NaN. [Problems casting NAN floats to int](https://stackoverflow.com/q/10366485). In practice it's not going to crash your program, but you'll get a number that depends on the target ISA and on exactly how the compiler optimized your code. In theory it's UB so literally anything can happen. – Peter Cordes Apr 12 '21 at 00:06
6

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)

Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
4

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.

ouah
  • 142,963
  • 15
  • 272
  • 331