on Thu, 10 Jul 2003 20:34:29 +0000 (UTC),
Okay, here's a question about the standard. What does it say about
unsigned/signed mismatches in a comparison statement:
char a = 3;
unsigned char b = 255;
if (a<b)
Now what's the real answer here? If a is converted to unsigned, then b>a.
But, if b is converted to signed,then a>b
What's the correct coversion
(what is the compiler supposed to do?)
5.9p2 tells us that the usual arithmetic conversions (5p9) are performed.
4.5p1 tells us that 'a' is promoted to signed int,
It also tells us that b is promoted to either signed int or unsigned
int, depending on the implementation, specifically:
,----
| An rvalue of type char, signed char, unsigned char, short int, or
| unsigned short int can be converted to an rvalue of type int if int
| can represent all the values of the source type; otherwise, the source
| rvalue can be converted to an rvalue of type unsigned int.
`----
Either way, it will still have the value 255 (I assume from your magic
number of 255, you're thinking of a platform with 8-bit characters and
you're concerned about sign-extention? Not a problem here
If b has been promoted to signed int (such as in an 8-bit char
environment), then the comparison is performed with signed integers, so
(a<b) yields true.
If b has been promoted to unsigned int, a is then also converted to
unsigned int (5p9) and the comparison is performed using unsigned
integers, and again (a<b) yields true.
In this last case (b promoted to unsigned, a converted to unsigned),
then the result is highly dependant on the actual value of a, as 4.7p3
says:
,----
| If the destination type is signed, the value is unchanged if it can be
| represented in the destination type (and bitfield width); otherwise,
| the value is implementation-defined.
`----
Since, in your example, a == 3, then it can comfortable fit inside an
unsigned int and hence is unchanged.
At least, that's the way _I_ read the standard
Regards,
Andy S.