为什么在下面的C++程序中2147453647*2147453647的乘积显示为1,-2147453648*-2147453648的乘积显示为0?

Why does the product of 2147453647*2147453647 show 1 and -2147453648*-2147453648 shows 0 in the below C++ program?

我已经声明了两个 int 变量:n1=2147483647(我的编译器的最大值)和 n2=-2147453648(最小值)。 n1*n1n2*n2的结果竟然是1和0。

为什么要这些值?如果和数据类型的范围有关,那能不能是任意值,或者int能容纳的最大值?

int main()
{
    int n1 = 2147483647;
    cout << "Product is : " << n1 * n1 << endl;

    int n2 = -2147483648;
    cout << "Product is : " << n2 * n2 << endl;

    return 0;
}

有符号整数溢出是未定义的行为 (reference)。

现在,如果您想知道这些特定值在您的特定环境中是如何产生的,它们很简单,就是结果的 32 least-significant 位 (LSB):

  • 2147483647*2147483647 等于 0x3fffffff00000001,其中的 32 LSB 是 0x00000001;
  • -2147483648*-2147483648 等于 0x4000000000000000,其 32 LSB 为 0x00000000.