here is the question:
in the Book ‘Computer Systems: A Programmer’s Perspective’ section 2.2.5
it said that if an unsigned value is comparing with a signed value, all values will be compared in the unisnged format. like this
if(-1 < 0u)
{
// will not print this line because -1 will be translated to 255.
printf("all changed to unsigned format");
}
I tried this code in VC6 SP6, the string was NOT outputed. And everything looks good because we all know that -1 was translated to 255.
but when I read the book ‘Expert C Programming Deep C Secrets’ section 1.10
It said that if my complier uses the ANSI C Standard, this code will print “-1 < (unsigned char)1: ANSI”:
if(-1 < (unsigned char)1)
{
printf("-1 < (unsigned char)1: ANSI");
}
else
{
printf("-1 NOT Less than (unsigned char)1: K&R");
}
The output I got was: -1 < (unsigned char)1: ANSI.
I’m using the VC6 SP6 complier.
and why is this happening?
according to the book ‘Computer Systems: A Programmer’s Perspective’
-1 < (unsigned char)1 will make -1 be translated as an unsigned value. so it will become sth like this:
255 < 1
and this should not print out the line -1 < (unsigned char)1: ANSI.
can anybody tell me why this is happening?
if(-1 < (unsigned char)1)In this case both operands are promoted to
int.if( -1 < 0u )In this case both operands are converted to
unsigned int.The following quotes prove me right.
And this (integral promotions):
To be perfectly honest, the quotes are from the C++03 standard, but they hold for C as well.