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

C++LoopsFor LoopConditional Statements

C++ Problem Overview


I've seen both of these two for statements:

for(i=0;i<10;i++) 

for(i=0;i!=10;i++)

I know they all stop when i reaches 10 , but it seems better to use the second one (I heard). What is the different?I also want to know when use iterator to access member of a vector, what is the difference between iterator condition < vec.end()and != vec.end()

C++ Solutions


Solution 1 - C++

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 <.

Solution 2 - C++

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.

Solution 3 - C++

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

Solution 4 - C++

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.

Solution 5 - C++

The best practice is to use != only with iterators (C++) and < otherwise. Never ever use == or != with floats/doubles. The following loop is an infinite loop:

for (double i = 0.0; i != 1.0; i += 0.1)
    printf("yes, I'm an infinite loop ;)");

Solution 6 - C++

!= would allow the test to evaluate true if the value of i exceeds 10, while < would cause it to evaluate false if i exceeded 10 or merely became equal to it.

If the value of i might change within the body of the loop, this could be a consideration.

If, however, you're just looking to do something a set number of times, < is more descriptive, but either would suffice. != should, for simple step-through-10-items-and-do-grunt-work kinds of loops, be considered suboptimal in terms of being explicit about your intent.

Solution 7 - C++

> I know they all stop when i reaches 10 , but it seems better to use > the second one(I heard).

That is a micro optimization. Use whatever makes more sense (and above < makes more sense).

> What is the different?

The 1st version uses the inequality operator !=, and the 2nd uses the less operator <.

Solution 8 - C++

I usually use < in for-loops for the reasons stated by others. In while-loops and more advanced for-loops though, != makes it much easier to reason about what my program does.

Say I want to find the position after the first run of '5's in an array like [5,5,5,3,5,2,3,2,0]. That is we want k such that 0 <= i < k => a[i] = 5:

int pos = 0;
// Inv: a[0..pos) = 5
while (pos != N && a[pos] == 5)
    pos = pos+1;

Once the loop has executed we know that the inverse of the loop guard is true: pos == N || a[pos] != 5. In either case we have the pos we want.

Now say we had used < in the loop guard, then all we would have known afterwards was pos >= N || a[pos] != 5, but that's not the situation we wanted to be in. Doing a lot more work, we can prove that we can't possible be in pos > N, but that seams like a waste of time compared to just using != in the loop guard.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionArcheosudoerusView Question on Stackoverflow
Solution 1 - C++Brendan LongView Answer on Stackoverflow
Solution 2 - C++Jonathan MView Answer on Stackoverflow
Solution 3 - C++fatView Answer on Stackoverflow
Solution 4 - C++COD3BOYView Answer on Stackoverflow
Solution 5 - C++SOReaderView Answer on Stackoverflow
Solution 6 - C++ChristopherView Answer on Stackoverflow
Solution 7 - C++BЈовићView Answer on Stackoverflow
Solution 8 - C++Thomas AhleView Answer on Stackoverflow