Re: how to avoid -Wconversion warning about float to integer conversion

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Hello Martin,

> recently i have actived the -Wconverion flag of g++-4.4.1 on my Ubuntu
> linux system. It brought up a warning
> (http://trac.wxwidgets.org/ticket/11252). Now my question: g++ warns
> about, that it may change the value. How to make do it correctly? Is
> there a function to check a float number fits into an integer?

Avoiding the warning is quite easy: do an explicit cast:
If you write:

float f = 2.1f;
int x = (int)f;

you won't obtain a warning.

Determining whether it is an integer is a bit more complex (at least I
don't remember a direct function right now). However:
if( ceil(f) == floor(f) )
will be a good start. If you want to be more precise, you should check
in addition, that f is not NAN:
if( isnormal(f) && ceil(f) == floor(f) )
should be more general. However, isnormal is only defined in C99...

Last remark: ceil and floor return floats - so in addition you can have
an overflow. I think, you are on the save side with a check like:
if ( isnormal(f) && ceil(f) == floor(f) && floor(f) < INT_MAX && floor(f) > INT_MIN )

INT_MIN and INT_MAX are defined in limits.h.

Axel

[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux