Safely compare integers of different types
Comparing different types of integers may not always produce the expected results. For example:
int x{ -3 }; unsigned y{ 7 }; if(x < y) puts("true"); else puts("false");
You may expect this code to print true
, and that's understandable. -3 is usually less than 7. But it will print false
.
The problem is that x
is signed and y
is unsigned. The standardized behavior is to convert the signed type to unsigned for the comparison. That seems counterintuitive, doesn't it? Indeed, you cannot reliably convert an unsigned value to a signed value of the same size, because a signed integer uses two's complement representation (which uses the most significant bit as a sign). Given the same sized integer, the maximum signed value is half that of an unsigned value. Using this example, if your integers are 32-bits, -3 (signed) becomes FFFF FFFD
(hexadecimal), or 4,294,967,293 (unsigned decimal), which is not less...