C++ expressions with unsigned and signed operands

For historical reasons in C++ still holds the following behavior when signed and unsigned numbers mix up in the same operand.

In a piece of code like the following:

unsigned int u=1;
int i=-1;
if( i < u )
    cout << "i < u" << '\n';
else
    cout << "i >= u" << '\n';

the outcome would be that the “if condition” is false, even if -1 < 1.

The reason is that a C++ rule (legacy of C rules) states that if two opereands are of the same size and one is unsigned and the other is signed, the signed one is preliminarly converted to unsigned before evaluating the operation.

Therefore here -1 (int) is converted to unsigned int and, due to 2-complement encoding, its “unsigned” representation is bigger than 1.

For an in-depth analysis on the consequent issues and possible approaches to deal with unsigned/signed peaceful living in the same expressions, see this great blog post from “It Hare”.

Leave a Reply