cast of float to unsigned char bug on ARM with 3.4.5 - when was it fixed?
John Love-Jensen
eljay@adobe.com
Thu Jan 10 15:23:00 GMT 2008
Hi Sam,
> I assume this is a know bug that got fixed in later gcc's.
> I have tried searching the gcc bug database with no luck.
It's not a GCC bug. Your code a C bug (if I may be so presumptuous to
describe using undefined C behavior as a "bug").
Since your code is performing undefined behavior, the output of all four
examples is correct.
>From "The C Programming Language" A.6.3 "The result is undefined if the
value will not fit in the space provided". After truncation, -30 does not
fit in 0 ... 255 range (assuming your unsigned char is 8-bit), hence
undefined behavior.
One way you could fix your code to have more consistent behavior is to use
an intermediate int.
The sample code:
====================
#include <stdio.h>
int main(void)
{
int i;
unsigned char n1;
float n2;
n2 = -30.33F;
i = (int)n2;
n1 = (unsigned char)i;
printf("n1: %d n2: %3.2f\n", n1, n2);
return 0;
}
====================
As long as an int is the same bit-size and is 2's complement represented on
the platforms being compared, that should product the same output.
HTH,
--Eljay
More information about the Gcc-help
mailing list