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

I almost never see a for loop like this:

for (int i = 0; 5 != i; ++i)
{}

Is there a technical reason to use > or < instead of != when incrementing by 1 in a for loop? Or this is more of a convention?


Solution 1:

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.

Solution 2:

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.

Solution 3:

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.

Solution 4:

You can have something like

for(int i = 0; i<5; ++i){
    ...
    if(...) i++;
    ...
}

If your loop variable is written by the inner code, the i!=5 might not break that loop. This is safer to check for inequality.

Edit about readability. The inequality form is way more frequently used. Therefore, this is very fast to read as there is nothing special to understand (brain load is reduced because the task is common). So it's cool for the readers to make use of these habits.

Solution 5:

And last but not least, this is called defensive programming, meaning to always take the strongest case to avoid current and future errors influencing the program.

The only case where defensive programming is not needed is where states have been proven by pre- and post-conditions (but then, proving this is the most defensive of all programming).