As you’ve noted, the problem with a condition of i >= 0 when it’s unsigned is that the condition is always true. Instead of subtracting 1 when you initialize i and then again after each iteration, subtract 1 after checking the loop condition:
for (unsigned i = v.size(); i-- > 0; )
I like this style for several reasons:
- Although
iwill wrap around toUINT_MAXat the end of the loop, it doesn’t rely on that behavior — it would work the same if the types were signed. Relying on unsigned wraparound feels like a bit of a hack to me. - It calls
size()exactly once. - It doesn’t use
>=. Whenever I see that operator in aforloop, I have to re-read it to make sure there isn’t an off-by-one error. - If you change the spacing in the conditional, you can make it use the “goes to” operator.