我正在阅读 CS:APP (一本 x86-64 汇编/低级教科书),它提到:
From
float
ordouble
toint
, the value will be rounded toward zero. For example,1.999
will be converted to1
, while−1.999
will be converted to−1.
Furthermore, the value may overflow. The C standards do not specify a fixed result for this case. Intel-compatible microprocessors designate the bit pattern [10 ... 00] (TMinw
for word sizew
) as an integer indefinite value. Any conversion from floating point to integer that cannot assign a reasonable integer approximation yields this value. Thus, the expression(int) +1e10
yields-2147483648
, generating a negative value from a positive one.
这里提到的兼容英特尔的微处理器是什么? x86
架构包括AMD系列?
无论如何,我有一台带有 Win10 64 位的 Intel i5 机器,并且我在 Visual Studio 下尝试过:
#include <iostream>
using namespace std;
int main() {
int b = (int)+1e10;
cout << b << endl;
}
并得到1410065408
作为输出。
我也尝试过int32_t
并得到 1410065408
也是。
那为什么我没有得到结果 -2147483648
这是 [10 ... 00]
正如书中所描述的那样?
最佳答案
即使所使用的处理器具有“任何无法分配合理整数近似值的从浮点到整数的转换都会产生此值。”,编译器不需要遵循该规则,因为它可以使用其他代码来实现目标。
特别是,可以在编译器时确定的值,如some_32_bit_int = (int)+1e10;
,可能会得到类似some_32_bit_int = 10000000000 & 0xFFFFFFFF的值;
或 1410065408
完全独立于处理器。
If the value of the integral part cannot be represented by the integer type, the behavior is undefined.
C17dr § 6.3.1.4 1
这本书描述的是处理器,而不是编译器。
关于c++ - 为什么表达式 (int) +1e10 不会产生 -2147483648 正如 CSAPP 所描述的那样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65260691/