c++ - 为什么表达式 (int) +1e10 不会产生 -2147483648 正如 CSAPP 所描述的那样?

标签 c++ x86 floating-point type-conversion undefined-behavior

我正在阅读 CS:APP (一本 x86-64 汇编/低级教科书),它提到:

From float or double to int, the value will be rounded toward zero. For example, 1.999 will be converted to 1, 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 size w) 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的值;141006540​​8 完全独立于处理器。

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/

相关文章:

linux - x86 NASM Linux 程序集中的 ATOI 问题

macos - 通过替换为 NOP 来修补 CALLL 在用户空间中有效,但在内核空间中无效

c - 如何手动设置等于 NaN 的 float 的位值?

c++ - std::chrono::time_point 设置为现在

c++ - C++ 中的 char[] 和 char[10] 有什么区别?

c++ - 如何使用 node.js 开发一个监听器来接收许多车辆跟踪数据(通过 tcp)?

c - C语言中最简单的操作无法正常工作

c++ - 普通数组上的 std::lower_bound 和 std::find

performance - 哪个英特尔微体系结构引入了ADC reg,0单uop特殊情况?

python - 为什么 Python 中的浮点除法用较小的数字更快?