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".
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With