为什么这个乘法中存在整数溢出?

Oli*_*ver 6 c++

我对这段代码感到困惑:

#include <climits>
#include <iostream>
int main(void) {
    using namespace std;
    cout << "long max " << LONG_MAX << endl;
    long x = 2 * 1024 * 1024 * 1024;
    cout << "2 * 1024 * 1024 * 1024 = " << x << endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我本来应该是2147483648,而不是我.使用unsigned似乎没有帮助.是什么赋予了?

long max 9223372036854775807
2 * 1024 * 1024 * 1024 = -2147483648
Run Code Online (Sandbox Code Playgroud)

Jes*_*ood 11

添加一些Ls*.long x = 2L * 1024L * 1024L * 1024L;

(从技术上讲,只要一个文字类型long,其他文字将被提升为long)

发生溢出2是因为int默认情况下类型是类型,溢出发生赋值之前.

请参阅整数文字,它解释了不同的文字.