On 5/12/2010 10:08 AM,
d wrote:
> hi
>
> Can someone tell me whats going on here. I'm using gcc 4.3.3 in linux.
> Have I missed something obvious in the code snippet below or is there some
> odd casting bug going on with gcc?
>
> $ cat t.c
> #include<stdio.h>
>
> main()
> {
> double d = -2.345;
> printf("%f\n",(double)(1 ? (int)d : (unsigned int)1));
> }
> $ cc t.c
> $ ./a.out
> 4294967294.000000
Right. (Well, it depends on the value of UINT_MAX, but on
most 32-bit systems this is what you should expect.)
> If you change unsigned int to unsigned char then you get -2 as expected as
> the result.
Right again.
Remember, every expression in C has a single type, fixed at
compile time and immutable thereafter. In particular, the type
of `x?y:z' is one type, not "sometimes the type of y and sometimes
the type of z, depending on x." So, what happens when y and z
start out as different types? The same thing that happens when
you compute `y+z' or `y>z' or pretty much anything else: The "usual
arithmetic conversions" are performed, and the result has the type
that those conversions produce. So, what's the type of `-2 + 1u'?
And what's the type of `1 ? -2 : 1u'?
By the way, if you crank up gcc's warning levels it will tell
you "warning: signed and unsigned type in conditional expression."
I think it's good practice to crank up the warnings as high as your
code can stand -- and even if you don't routinely put them to the
max, you should *definitely* do so when confronted with a mystery.
--
Eric Sosman
lid