Francois Grieu <fg****@gmail.comwrites:
one of my C compiler (Keil C51) evaluates the constant expression
1<<(1?1:1) < 0x9999
to the value 1.
// this returns 0, much to my surprise
unsigned char bug4_a(void)
{
return 1<<(1?1:1) < 0x9999;
}
Can this find a satisfactory explanation under some definition of the
C language ?
The behavior is inconsistent with the C standard. (If Keil C51 claims
to conform, it's a bug; if it doesn't, it may or may not be a bug,
depending on what, if anything, its documentation says).
I'll assume that types int and unsigned int are 16 bits.
1<<(1?1:1) has the value 2 and is of type int.
0x9999 has the value 39321 and is of type unsigned int.
The "usual arithmetic conversions" are applied to the operands of "<".
This converts the left operand, 2, from int to unsigned int.
So the expression 1<<(1?1:1) < 0x9999 is equivalent to 1U < 39321U,
which yields the int value 1. The return statement converts this to
unsigned char, yielding (unsigned char)1.
My guess is that a bug in the compiler is causing it to do the "usual
arithmetic conversions" incorrectly in this case. It's probably
converting the right operand to signed int rather than converting the
left operand to unsigned int, changing the comparison:
(int)2 < (unsigned)39321
to
(int)2 < (int)-26215
which yields 0.
Try replacing 0x9999 with 0x7fff and 0x8000 and see what happens.
[snip]
--
Keith Thompson (The_Other_Keith) <ks***@mib.org>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"