Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overflow after an implicit cast

When I try to make an implicit cast from a double to an unsigned long, I have an overflow warning : "warning: overflow in implicit constant conversion [-Woverflow]".

Here is the instruction :

unsigned long ulongMax = pow(2.0, 64.0) - 1; 

But when I explicitly cast this like below, it's ok !

unsigned long ulongMax = (unsigned long) (pow(2.0, 64.0) - 1);

I don't understand why i have a warning, the result (18446744073709551615) is the same than ULONG_MAX from the header "limits.h".

like image 954
Burrich Avatar asked Nov 22 '25 08:11

Burrich


1 Answers

pow(2.0, 64.0) returns a double.

However (assuming a normal IEEE754 system), the values pow(2.0, 64.0) and pow(2.0, 64.0) - 1 are actually equal. This is because we are outside the range where adjacent integers are exactly representible in double. (Of course, a 64-bit double cannot represent all 64-bit integers).

Now, out-of-range casts from floating-point to integer type causes undefined behaviour, with no diagnostic required.

Your compiler is trying to be helpful by warning you about this undefined behaviour in the first case, but (presumably) it treats the addition of the cast as a message from you saying "I don't want to hear this warning".

like image 73
M.M Avatar answered Nov 23 '25 23:11

M.M