This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Re: cast of float to unsigned char bug on ARM with 3.4.5 - when was it fixed?
- From: John Love-Jensen <eljay at adobe dot com>
- To: Sam Ravnborg <sam at ravnborg dot org>, MSX to GCC <gcc-help at gcc dot gnu dot org>
- Date: Wed, 09 Jan 2008 07:51:49 -0600
- Subject: Re: cast of float to unsigned char bug on ARM with 3.4.5 - when was it fixed?
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