奇怪的溢出分配2*1024*1024*1024
void main()
{
long long ll = 2 * 1024 * 1024 * 1024;
unsigned long long ull = (2 * 1024 * 1024 * 1024);
std::cout << ll << "n" << ull;
}
我使用 Visual Studio 2019 的输出是
-2147483648
18446744071562067968
我不知道为什么这里会发生溢出,请帮忙
回答
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;
}
I put an online version of this fixed code here:
https://ideone.com/5QkEls
- Makes more sense to _lead_ the multiplication chain with `LL` so `2LL * 1024 * 1024 * 1024`. Now the product is correct even if `int` was 16-bit.