What do these two signed/unsigned comparisons print?
Predict what the two comparisons print on a typical platform with a 16-bit short and a 32-bit int.
short s = -1;
unsigned short us = 1;
int i = -1;
unsigned u = 1;
std::cout << (s < us) << (i < u);Determine the output and explain each comparison.
10. short and unsigned short are both promoted to int, which holds all their values, so s < us is -1 < 1, true. int and unsigned are not promoted: -1 converts to UINT_MAX, so i < u is false.
- Applying the
int/unsignedrule toshortoperands, forgetting that integer promotion tointhappens first - Expecting
unsigned shortto promote tounsigned intbecause it is unsigned, whenintholds all its values
- On which platform would
unsigned shortbe promoted tounsigned intinstead ofint? - Why does
for (size_t i = n - 1; i >= 0; --i)loop forever?
Before the comparison the operands go through two steps. First integer promotion: types narrower than int (short, unsigned short, char) become int if int holds all their values, as it does with a 16-bit short and a 32-bit int. Then the usual arithmetic conversions bring the operands to a common type, and for int with unsigned that type is unsigned.
short s = -1;
unsigned short us = 1;
std::cout << (s < us); // int(-1) < int(1) → 1
int i = -1;
unsigned u = 1;
std::cout << (i < u); // 4294967295u < 1u → 0
std::cout << std::cmp_less(i, u); // C++20, -1 < 1 → 1With -Wsign-compare the compiler warns only about the second comparison: after promotion both operands of the first are already int. To compare a signed and an unsigned value by their mathematical value, use std::cmp_less from <utility> (C++20).