Comparing signed and unsigned integers safely
The C++ language features a variety of integral types: short
, int
, long
, and long long
, as well as their unsigned counterparts unsigned short
, unsigned int
, unsigned long
, and unsigned long long
. In C++11, fixed-width integer types were introduced, such as int32_t
and uint32_t
, and many similar others. Apart from these, there are also the types char
, signed char
, unsigned char
, wchar_t
, char8_t
, char16_t
, and char32_t
, although these are not supposed to store numbers but characters. Moreover, the type bool
used for storing the values true
or false
is also an integral type. The comparison of values of these types is a common operation but comparing signed and unsigned values is error-prone. Without some compiler-specific switches to flag these as warnings or errors, you can perform these operations and get unexpected results. For instance, the comparison -1 < 42u
(comparing signed -1 with unsigned 42) would yield false
. The C++20 standard...