什么时候将双精度转换为整数是未定义的行为

Casting double to integer when is it undefined behaviour

所以如下:

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

不是未定义的行为,因为 244 可以放入 int 我做对了吗? 否则,如果它是更大的值而不是 244 不适合在 int 中,这将是未定义的,我做对了吗?

我更感兴趣的是 C 是如何做到这一点的。但是在这种情况下 w.r.t 与 C++ 有区别吗?

来自我最喜欢的 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).

所以是的,你是对的。 (对于 C++,但有人已经为 C 发布了几乎相同的标准引用)

如果整数部分不能用整数类型表示,C 中的未定义行为。

(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"

C++11, 4.9p1.

中 C++ 中的类似措辞

来自[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.

因此,例如,将 66666.66 转换为 int16_t 将是未定义的行为,但转换 66.66 就可以了。