mach mach - 1 month ago 4x
C++ Question

C++ : overflow in implicit constant conversion [-Woverflow]

long long sum;

Above code in C++ gives the error:

overflow in implicit constant conversion [-Woverflow]

While following code runs fine:

long long sum;

What might be the issue ?


The problem is that long longis too small to hold the result of pow(10,19).

long long is usually 64 bits, and a 64 bit integer can hold approx. 1.8*10^19 different values. However, since it is signed, you only get the half of it (the other half is for negative values). And the half of that is 0.9*10^19, which is apparently less than 10^19.

Another issue (but not the reason of the warning / overflow) here is that the pow() function returns a floating-point value. So even if the result would fit into long long - which it does not - you might loose some precision and not get the exact integer result.

Edit: Of course, you could use unsigned long long for this case instead. That would be enough for 10^19, but not for 10^20. So you are just defering the problem to a later time when you are using similarily large numbers that don't fit into unsigned long long.