简体   繁体   中英

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".

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".

the warning means that it potentialy could loss precision if pow(2.0, 64.0) - 1 were too big or with fractional part (say 1.7*10^308, which is the max for doubles) or 0.9, which would be truncated to 0).

The reason you don't get the warning when using explicit cast (unsigned long) (pow(2.0, 64.0) - 1) is that being explicit you say "I actually want to get a unsigned long from this double (whatever the nasty consequences of it)"

The most likely reason why you get a warning is that unsigned long on your platform is 32-bit, not 64-bit, in size.

If you switch to a 64-bit unsigned, the warning would go away:

unsigned long long ulongMax = pow(2.0, 64.0) - 1; 
printf("%llu", ulongMax);

Demo.

Explicit cast eliminates the warning because essentially it tells the compiler that you are aware of what is going on, and you want it to be quiet and do as you say.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM