Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

g++ warn when double/float is converted to unsigned integer without using -Wconversion [duplicate]

Tags:

c++

c

g++

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.

like image 719
KyleL Avatar asked Dec 06 '12 20:12

KyleL


People also ask

What happens when you cast a float to unsigned int?

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.

Do we lose any data when we convert from float to int data type?

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.

How do I convert unsigned to signed?

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.

Is unsigned int a float?

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


1 Answers

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.

like image 147
Mark B Avatar answered Oct 17 '22 21:10

Mark B