You should use whichever of <
, <=
, !=
etc. best expresses your application logic, but if there's no reason to prefer any particular style, then be consistent. In informing that decision, the <
and !=
operators have the advantage of allowing comparisons between 0-based indices and sizeof
or STL-style size
/ length
values, as in:
for (size_t i = 0; i < my_vector.size(); ++i)
...
The <
and <=
operators sometimes guard against incrementing past the terminating value (if you've got another condition inside the loop under which you increment/add-to i
, or there's some floating point rounding/representation disparity). Not often actually significant, but saving an occasional bug is better than nothing.
Given '<' is the intersection of these two sets, it's a popular choice. To my mind, <
also communicates the states under which the loop runs... a more positive assertion rather than the !=
style. In general, negative assertions are discouraged in programming (e.g. bool invalid
is more complicated to get your head around reliably than bool valid
, especially in complex boolean expression and when double-negatives are introduced).
This is of course for numeric types. Other types may imply other styles... for example, use of != sentinel
. I prefer to have the choice of operator help document these usage implications of the type, though that's a personal choice and arguably redundant.
Otherwise, preincrement can be more efficient for complicated types than post- as it avoids a temporary.