This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: Why does (unsigned short)-1.3 == 0 and not 65535? (But only if optimizing with GCC 4.x)


Jack Lloyd <lloyd@randombit.net> writes:

> int main()
>    {
>    double d = -1.3;
>    unsigned short x = (unsigned short)d;
>    printf("%d\n", x);
>    }

The C99 standard says that when converting floating point to integer,
the value is first truncated toward zero.  If the value of the
integral part cannot be represented by the integer type, the behaviour
is undefined.  This means that converting a negative floating point
value <= -1.0 to an unsigned integer type is undefined, and the code
may act unpredictably.


> Secondly, can someone tell me if there is a warning I can use to tell
> me when this is happening? The code compiles cleanly with (or without)
> optimizations using "-Wall -Wextra -Wconversion". In this specific
> case, I can get the behavior I want using
>   (unsigned short)(int)d;

Adding the cast works because -1 can be represented in the type int,
and conversions from signed integer types to unsigned integer types
are defined to do the obvious thing.

Unfortunately, while gcc warns about conversions which have no
explicit cast, I don't think there is any option to warn about an
explicit cast which happens to be invalid.

Ian


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]