Strange overflow assigning 2 * 1024 * 1024 * 1024

Viewed 252
void main()
{
    long long ll = 2 * 1024 * 1024 * 1024; 
    unsigned long long ull = (2 * 1024 * 1024 * 1024);
    std::cout << ll << "\n" << ull;
}

My output with Visual Studio 2019 is

 -2147483648
18446744071562067968

I have no idea why overflow is happening here, please help

1 Answers

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

Related