In a "for" statement, should I use `!=` or `<`?

for(i = start; i != end; ++i)

This is the "standard" iterator loop. It has the advantage that it works with both pointers and standard library iterators (you can't rely on iterators having operator< defined).

for(i = start; i < end; ++i)

This won't work with standard library iterators (unless they have operator< defined), but it does have the advantage that if you go past end for some reason, it will still stop, so it's slightly safer. I was taught to use this when iterating over integers, but I don't know if it's actually considered "best practice".

The way I generally write these is to prefer <.


Both will work in most situations.

If for some reason the body of code executed in the loop changes i to something greater than 10, the first version will stop looping, but the second will execute forever.


My everyday practice is to use < when I iterate cycle with simple types such as integers and to use != when I work with stl-kind iterators


for ( initialization ; termination condition ; iteration )

For each of those , choose youself the best one to fit your requirements, for termination condition you can use any of the binary conditional operators such as > ,< ,>= ,<= ,!=

For your given question , consider a random case in which,

for(i=0;i!=10;i++)
{
 .
 .
 i=11; //somewhere if the loop variable is changed to a value greater than 10 (this assumption is solely for demo)
 .
 .
 .
}

In this case, the loop turns out to be infinite. rather if you use a condition i<10, this works as usual. so my point is that the first approach is a bit more safer to set condition strictly.