c - Why is an unsigned int 1 lower than a char y -1? -
main() { unsigned x=1; char y=-1; if(x>y) printf("x>y"); else printf("x<=y"); } i expected x>y. when changed unsigned int signed int, got expected results.
if char equivalent signed char:
charpromotedint(integer promotions, iso c99 §6.3.1.1 ¶2)- since
int,unsignedhave same rank,intconvertedunsigned(arithmetic conversions, iso c99 §6.3.1.8)
if char equivalent unsigned char:
charmay promoted eitherintorunsigned int:- if
intcan representunsigned charvalues (typically becausesizeof(int) > sizeof(char)),charconvertedint. - otherwise (typically because
sizeof(char)==sizeof(int)),charconvertedunsigned.
- if
- now have 1 operand either
intorunsigned, ,unsigned. first operand convertedunsigned.
integer promotions: expression of type of lower rank int converted int if int can hold of values of original type, unsigned otherwise.
arithmetic conversions: try convert larger type. when there conflict between signed , unsigned, if larger (including case 2 types have same rank) type unsigned, go unsigned. otherwise, go signed in case can represent values of both types.
conversions integer types(iso c99 §6.3.1.3):
conversion of out-of-range value unsigned integer type done via wrap-around (modular arithmetic).
conversion of out-of-range value signed integer type implementation defined, , can raise signal (such sigfpe).
Comments
Post a Comment