Binary operations between different integral types are performed in a โgeneralโ type defined by the so-called ordinary arithmetic transformations (see language specification, 6.3.1.8). In your case, the "generic" type is unsigned int . This means that the operand int (your b ) is converted to unsigned int before comparison, as well as for performing subtraction.
When -1 converted to unsigned int , the result is the maximum possible value of unsigned int (same as UINT_MAX ). Needless to say, it will be greater than the unsigned value of 1000 , which means that a > b really false and a really small compared to (unsigned) b . if in your code should resolve to else branches, as was the case in your experiment.
The same conversion rules apply to subtraction. Your ab really interpreted as a - (unsigned) b , and the result is of type unsigned int . Such a value cannot be printed using the %d format specifier, since %d only works with signed values. Your attempt to print it with %d leads to undefined behavior, so the value that you see printed (even if it has a logical deterministic explanation in practice) makes absolutely no sense from the point of view of C.
Edit: Actually, I could be wrong about undefined behavior. According to the specification of the C language, the common part of the range of the corresponding type, with and without signature, must have an identical representation (meaning, according to footnote 31, "interchangeability as arguments for functions"). Thus, the result of the expression a - b not specified 1001 , as described above, and if I do not miss something, it is legal to print this unsigned value with the %d specifier, since it falls into the positive range of int . Printing (unsigned) INT_MAX + 1 with %d will be undefined, but 1001u is fine.
AnT Jan 18 '10 at 9:37 2010-01-18 09:37
source share