I think this is a good illustration of why one should not use type
casting to perform algorithmic operations. You should operate on the
date and test the resulting value to ensure it will fit within the new type.
I'm assuming here that in the actual code it is not known whether d is
positive or negative. But type casting a possibly negative value into an
unsigned value is simply asking for your code to break.
I'm a big fan of writing code that explicitly shows each step in an
algorithm one statement at a time. If the operations are in a loop, and
testing shows that the loop is slowing things down too much, then
obscure and tricky code may be in order, but only with good commenting.
The maintenance programmer, perhaps you at a later date, will appreciate
being able to follow simple code.
--Bob
On 3/24/2010 1:58 PM, Ian Lance Taylor wrote:
Jack Lloyd<lloyd@xxxxxxxxxxxxx> 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