Is there a technical reason to use > (<) instead of != when incrementing by 1 in a 'for' loop? Is there a technical reason to use > (<) instead of != when incrementing by 1 in a 'for' loop? c c

Is there a technical reason to use > (<) instead of != when incrementing by 1 in a 'for' loop?


while (time != 6:30pm) {    Work();}

It is 6:31pm... Damn, now my next chance to go home is tomorrow! :)

This to show that the stronger restriction mitigates risks and is probably more intuitive to understand.


There is no technical reason. But there is mitigation of risk, maintainability and better understanding of code.

< or > are stronger restrictions than != and fulfill the exact same purpose in most cases (I'd even say in all practical cases).

There is duplicate question here; and one interesting answer.


Yes there is a reason. If you write a (plain old index based) for loop like this

for (int i = a; i < b; ++i){}

then it works as expected for any values of a and b (ie zero iterations when a > b instead of infinite if you had used i == b;).

On the other hand, for iterators you'd write

for (auto it = begin; it != end; ++it) 

because any iterator should implement an operator!=, but not for every iterator it is possible to provide an operator<.

Also range-based for loops

for (auto e : v)

are not just fancy sugar, but they measurably reduce the chances to write wrong code.