Possible Duplicate:
g++ -Wall not warning about double-> int cast
Per the question here, direct conversion from double/float to unsigned integer is not portable. I found I had a few cases in my code where this happens and I would like to tell g++ to warn me if this occurs, but I can't find such an option. Does anyone know if there is an option to do this?
Note: I do see -Wconversion, but that also warns about all kinds of other conversions that I don't care about (like converting int to unsigned int, which is portable per the standard).
Edit: Here's a code example for which I would like to see a warning:
double dblNumber = -234;
unsigned long uintNumber = dblNumber;
On one version of g++, this gives me an integer value of 0xFFFFFF16 (which is -234 in 2's complement) . On another it gives me 0. Clearly the code is ambiguous, which is why it is understandably not considered portable.
1 When a finite value of real floating type is converted to an integer type other than _Bool, the fractional part is discarded (i.e., the value is truncated toward zero). If the value of the integral part cannot be represented by the integer type, the behavior is undefined.
Any conversion from a floating point type to an integral type is a narrowing conversion because the fractional portion of the floating point value is discarded and lost.
To convert a signed integer to an unsigned integer, or to convert an unsigned integer to a signed integer you need only use a cast. For example: int a = 6; unsigned int b; int c; b = (unsigned int)a; c = (int)b; Actually in many cases you can dispense with the cast.
'unsigned int' and 'float' both use 32 bits to store values. Since a float has a larger range, it necessarily sacrifices some precision. This means that there are some unsigned int values that cannot be accurately represented in a float.
I know you said you don't want to use -Wconversion
but it warns on the problem you care about, and at least in g++ 4.5 doesn't warn when converting long
to unsigned long
(for example). For any other cases that it warns where you're performing a legal desired conversion, just cast it. Your future maintainers will thank you greatly for making it explicitly clear that a known conversion is being done rather than guessing whether it's intentional or not from the code context.
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