2
#include <iostream>
using namespace std;

int main() {

    long long a=2501*2501*2501;
    cout<<a;

    return 0;
}

I tried unsigned long long too and all the time it gives some gibberish answer. I checked the capacity of long long and it can hold this value.

Chintan Shah
  • 935
  • 2
  • 9
  • 28

1 Answers1

8

The long long can definitely hold this value. The problem is that the expression that you are using to compute it, i.e. 2501*2501*2501, is an int expression. The compiler computes the result using integers. This causes an overflow, because the result does not fit in 32 bits. Hence the result becomes invalid before the compiler knows that the value goes into a long long variable.

Add LL suffix to one of the numbers to fix the problem:

long long a=2501LL*2501*2501;

Demo.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • 32 bits is a typical size for `int`, but the standard only guarantees that it's at least 16. For that matter, `int` *could* be 64 bits. – Keith Thompson Jan 29 '15 at 17:07
  • Is there any reason not to put `LL` on the end of every integer literal? I wish that integer literals were 'typeless' – Aaron McDaid Jan 29 '15 at 17:12
  • @KeithThompson Right, 32 was only my guess, knowing that something wrong is happening. The chances of hitting a non-embedded C compiler with `int` size of less than 32 bits are small these days, so I took my chance here. – Sergey Kalinichenko Jan 29 '15 at 17:13
  • @AaronMcDaid Readability would be one such reason. Generally, though, the compiler should issue a warning about the overflow (and it's a good idea to treat all warnings as errors). – Sergey Kalinichenko Jan 29 '15 at 17:14