奇怪的溢出分配 2 * 1024 * 1024 * 1024

Doe*_*eee 2 c++ overflow visual-studio c++11

void main()
{
    long long ll = 2 * 1024 * 1024 * 1024; 
    unsigned long long ull = (2 * 1024 * 1024 * 1024);
    std::cout << ll << "\n" << ull;
}
Run Code Online (Sandbox Code Playgroud)

我使用 Visual Studio 2019 的输出是

 -2147483648
18446744071562067968
Run Code Online (Sandbox Code Playgroud)

我不知道为什么这里会发生溢出,请帮忙

dre*_*rjm 6

In both cases the calculation is done using integers because all the values on the right are integer literals. 2 * 1024 * 1024 * 1024 is 2,147,483,648 which 1 larger than the max 32 bit int so this part of the calculation is overflowing. To fix do the first calculation as long long using long long ll = 2LL * 1024 * 1024 * 1024; and the second calculation as an unsigned long long using unsigned long long ull = 2ULL * 1024 * 1024 * 1024;

You can learn more about integer literals here: https://en.cppreference.com/w/cpp/language/integer_literal

Here is the fixed code:

#include <iostream>
#include <limits>

using namespace std;

int main()
{
    long long ll = 2LL * 1024 * 1024 * 1024; 
    unsigned long long ull = 2ULL * 1024 * 1024 * 1024;
    std::cout << ll << "\n" << ull;
}
Run Code Online (Sandbox Code Playgroud)

I put an online version of this fixed code here: https://ideone.com/5QkEls

  • 用“LL”引导乘法链更有意义,因此“2LL * 1024 * 1024 * 1024”。现在,即使“int”是 16 位,产品也是正确的。 (2认同)