main() {
if ( -1 < (unsigned char) 1 )
printf("less than");
else
printf("NOT less than");
}
Prints less than
. Because, (unsigned char) 1
is converted to (signed char) 1
and then: (signed) -1 < (signed) 1
, thus output is less than
.
But if I change the above code to if ( (-1 < (unsigned int) 1 )
then the output is NOT less than
.
So it's obvious that when I change unsigned char to unsigned int:
- (signed) -1 is converted to unsigned int [exactly opposite is happening]
- since -1 is stored as 2's compliment of 1; the bit-pattern is evaluated as 255 (probably)
- thus 255 < 1 will evaluate to false and else will execute.
- even if you substitute
int a = -1;
in place of '-1' same result
Questions:
during signed and unsigned arithmetic...how to be sure if signed will be converted to unsigned or vice versa.
why is conversion different for arithmetic between unsigned char and char : apparently unsigned is converted to signed and unsigned int and int : apparently signed is converter to unsigned
PS: I know this is not compiler dependent..so don't say it is.