Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++11

long long sum;
sum=pow(10,19);
cout<<sum;

Above code in C++ gives the error:

overflow in implicit constant conversion [-Woverflow]

While following code runs fine:

long long sum;
sum=pow(10,18);
cout<<sum;

What might be the issue ?

like image 280
mach Avatar asked May 18 '26 09:05

mach


2 Answers

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.

like image 141
Striezel Avatar answered May 20 '26 22:05

Striezel


log2(10^18) ~ 59.80
log2(10^19) ~ 63.12

A signed long long is likely to be 64bit with 1bit reserved for the sign, thus 10^18 nicely fits, but 10^19 doesnt.

The C++ standard also only gurantees that numbers up to 2^63-1 can be stored in a long long.

pow is also operating on floating points. Its result will not be exact. Therefore saving it to an integer is likely a mistake anyway.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!