c - Comparison operation on unsigned and signed integers -
see code snippet
int main() { unsigned int = 1000; int b = -1; if (a>b) printf("a big! %d\n", a-b); else printf("a small! %d\n", a-b); return 0; }
this gives output: small: 1001
i don't understand what's happening here. how > operator work here? why "a" smaller "b"? if indeed smaller, why positive number (1001) difference?
binary operations between different integral types performed within "common" type defined called usual arithmetic conversions (see language specification, 6.3.1.8). in case "common" type unsigned int
. means int
operand (your b
) converted unsigned int
before comparison, purpose of performing subtraction.
when -1
converted unsigned int
result maximal possible unsigned int
value (same uint_max
). needless say, going greater unsigned 1000
value, meaning a > b
indeed false , a
indeed small compared (unsigned) b
. if
in code should resolve else
branch, observed in experiment.
the same conversion rules apply subtraction. a-b
interpreted a - (unsigned) b
, result has type unsigned int
. such value cannot printed %d
format specifier, since %d
works signed values. attempt print %d
results in undefined behavior, value see printed (even though has logical deterministic explanation in practice) meaningless point of view of c language.
edit: actually, wrong undefined behavior part. according c language specification, common part of range of corresponding signed , unsigned integer type shall have identical representation (implying, according footnote 31, "interchangeability arguments functions"). so, result of a - b
expression unsigned 1001
described above, , unless i'm missing something, legal print specific unsigned value %d
specifier, since falls within positive range of int
. printing (unsigned) int_max + 1
%d
undefined, 1001u
fine.
Comments
Post a Comment