2
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

Doeee
  • 43
  • 4
  • 3
    `main` should return `int`. – Pete Becker Dec 13 '20 at 23:12
  • In both cases you are doing the calculation as an int and overflowing. All the numbers on the right hand side are integers. Try `std::cout << 2 * 1024 * 1024 * 1024ull << std::endl;` – drescherjm Dec 13 '20 at 23:22
  • See also [Why write 1,000,000,000 as 1000*1000*1000](https://stackoverflow.com/a/40637622/2410359). – chux - Reinstate Monica Dec 14 '20 at 00:05
  • Tip: Use things like `uint64_t ull` from [``](https://en.cppreference.com/w/cpp/types/integer) instead of madness like `unsigned long long long long plz be long ull` where it's unclear what you'll actually get. – tadman Dec 14 '20 at 00:31

1 Answers1

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;
}

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

drescherjm
  • 10,365
  • 5
  • 44
  • 64