Search code examples
c++data-structureslong-integerunsignedunsigned-integer

Unexpected outputs are coming by only changing the data type


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?


Solution

  • 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