Comparison between signed
and unsigned
integers is dangerous because it produces counter-intuitive results due to
implicit conversions. When a signed integer is compared to an unsigned one, the former might be converted to unsigned. Since C++20, the conversion
preserves the two’s-complement bit pattern of the signed value that always corresponds to a large unsigned result. For example, 2U <
-1
is true
.
This rule raises an issue when an unsigned integer is compared with a negative value.
What is the potential impact
Integer comparisons are often used in branch and loop conditions. An unexpected result from one of these conditions can lead to hard-to-detect
issues, such as unexpected infinite loops.
For example, using container size functions in a comparison can lead to such a problem since these return an unsigned integer value.