In the Google C++ Style Guide, on the topic of \"Unsigned Integers\", it is suggested that
Because of historical accident, the C++ standard also uses unsi
As stated, mixing unsigned
and signed
might lead to unexpected behaviour (even if well defined).
Suppose you want to iterate over all elements of vector except for the last five, you might wrongly write:
for (int i = 0; i < v.size() - 5; ++i) { foo(v[i]); } // Incorrect
// for (int i = 0; i + 5 < v.size(); ++i) { foo(v[i]); } // Correct
Suppose v.size() < 5
, then, as v.size()
is unsigned
, s.size() - 5
would be a very large number, and so i < v.size() - 5
would be true
for a more expected range of value of i
. And UB then happens quickly (out of bound access once i >= v.size()
)
If v.size()
would have return signed value, then s.size() - 5
would have been negative, and in above case, condition would be false immediately.
On the other side, index should be between [0; v.size()[
so unsigned
makes sense.
Signed has also its own issue as UB with overflow or implementation-defined behaviour for right shift of a negative signed number, but less frequent source of bug for iteration.