0
unsigned long long int s=0;
s=191689628 +646033877 +109099622 +798412961 +767677318+ 190145527 +199698411;
cout<<s<<endl;

return 0;

Output to above code is 18446744072317341664.

unsigned long int s=0;

s=191689628 +646033877 +109099622 +798412961 +767677318+ 190145527 +199698411;
cout<<s<<endl;

return 0;

OUTPUT to above code is 2902757344, this is the correct value.

why unsigned long long int is giving an unpleasant output?

  • 1
    What happens in the first scenario if you add `ULL` suffixes to each of the numbers? Or in the second scenario, adding `UL` to each of the numbers? The [**undefined behavior**](https://stackoverflow.com/a/4105123/4641116) causes the program to crash on my machine. – Eljay Jul 29 '21 at 18:26
  • gcc gives one a hint: `warning: integer overflow in expression [-Woverflow]` and produces 18446744072317341664 for both declarations. – Suthiro Jul 29 '21 at 18:27
  • I suppose that @Eljay is right about `ull` stuff. The 191689628 and all other numbers are _signed integers_ 4 bytes long. The compiler adds 'em together, the sum is greater than the capacity of 32-bit signed integer so an overflow occurs. The `s` is assigned _after_ overflow has occurred. Adding a `ull` or `ul` to the first number prevents overflow since the compiler first allocates 64-bit unsigned integer and adds the rest. – Suthiro Jul 29 '21 at 18:35
  • @Suthiro "*and produces 18446744072317341664 for both declarations*" - that would be true only if `long` is 64bit in size. Not if it is 32bit in size, which is clearly true in the OPs case. – Remy Lebeau Jul 29 '21 at 18:46

1 Answers1

2

All of your integer literals are using the int type, so the result of 191689628 + 646033877 + 109099622 + 798412961 + 767677318 + 190145527 + 199698411 exceeds the highest int value and thus overflows. Signed integer overflow is undefined behavior.

You are then assigning the overflowed values (which are negative) to unsigned types, which result in huge values for their respective types. unsigned long long int is (typically) larger than unsigned long int, so the difference is going to be much greater. That is why you are seeing these results.

To avoid the overflow, use unsigned literals to begin with.

In the first example, add the ull or ULL suffix to each literal to make them all unsigned long long int instead of int:

unsigned long long int s = 0;
s = 191689628ULL + 646033877ULL + 109099622ULL + 798412961ULL + 767677318ULL + 190145527ULL + 199698411ULL;
cout << s << endl;

In the second example, use the ul or UL suffix instead:

unsigned long int s = 0;
s = 191689628UL + 646033877UL + 109099622UL + 798412961UL + 767677318UL + 190145527UL + 199698411UL;
cout << s << endl;

Online Demo

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770