views:

302

answers:

12
int n = 5;
for(int i = 0;i!=n;i++)//condition !=
{
//executing 5times
}

int n = 5;
for(int i = 0;i<n;i++)//condition <
{
//executing 5times

}

Which one is preferred?

This was example from "Accelerated C++ : practical programming by example / Andrew Koenig, Barbara E. Moo." Just wanted to know why the Author prefers the first one

+1  A: 

<n is the most used (my opinion)

karlis
benlumley, please remove it, it was not empty, it was a bug.if you write <n at the beginning of your message nothing is displayed!!
karlis
+1 to fix the unjust -1
Asaf R
A: 

I can't see that it matters, aren't there more important things to worry about?

I always use the latter, and that's what I've seen most.

Someone is sure to shoot me down over it though ....

benlumley
Exactly, you've seen it most. Generally it's always better to code as other coders will expect - it makes maintenance easier and is common courtesy to your peers
Cruachan
+3  A: 

I would say < as it captures a wider set of conditions. Suppose that n wasn't constant but returned from a function which on rare occasions returned -1. In that event, you'd have a much longer loop (until the int wraps around to a -ve value!) with the != version of the loop.

Paul Dixon
+12  A: 

The second. For two reasons

  1. The less than (or sometimes <=) is the usual way that most coder write these, and it's better to stick to convention if possible - the != will probably make most coders look twice to check if there's something odd in the loop whereas the < will be instantly understood.

  2. The != depends on an exact condition. If the interior of the loop is modified during maintenance and i accidentally incremented inside the loop then you would end up with an infinite loop. Generally it's always better to make your termination condition as wide as possible - it's simply more robust.

2 is of course the reason why 1.

Cruachan
+3  A: 

Using condition < is much better because it reduces the possibility of stepping over your sentinel value and falling into an infinite loop.

Evan Fosmark
+1  A: 

I usually do the second way using <. But thinking of using != since stl iterators in c++ works this way.

yesraaj
+1  A: 

The second. It will always complete at some point (assuming you're not doing anything funny like playing with the counter's value inside the loop).

I've never seen the first used, atleast, not in that way.

Matthew Scharley
+1  A: 

As given in the question, both loops are equivalent. In real code, however, it is typical that things are a bit more complicated, and in that case, the "i < n" condition tends to be tiny bit more safe. If, for example, i might increase by more than one, it might go past n and then the "i != n" version would result in an eternal loop.

This is a case of defensive programming. It is not universally accepted: some people prefer to make sure things fail as spectacularly as possible so that bugs are found early on. The defensive style may hide small problems like that. However, if you want to catch all bugs, you might as well go all the way:

int n = 5;
int i = 0;
while (i != n) {
    int old_i = i;
    // the real stuff of the loop here
   ++i;
   assert(i == old_i + 1);
}

(Or, even better, use a langauge that supports synxtax for specifying pre- and post-conditions and loop invariants natively.)

The book "C Traps and Pitfalls" by Andrew Koenig (see http://en.wikipedia.org/wiki/C_Traps_and_Pitfalls for starters) is probably interesting to you if you like to ponder on this kind of question.

Lars Wirzenius
A: 

"i < n" is better. Because if you use "i != n" and in some case your initial i is larger than n, you will enter an infinite loop.

Igor Oks
No infinite loop, but an ovrflow error ;-)
Gamecat
+1  A: 

I believe this is a better alternative if you're optimizing for speed:

int n = 5;
for(int i = n;i > 0;i--)
{
//executing 5times
}

The reason for that is that comparing with 0 is faster.

No -1, but you're probably going to be accessing an array indexed by i inside that loop, and CPUs do a better job of prefetching memory to cache when it's being accessed in increasing order. The 1ns you bought comparing with 0 will be drowned out by 70ns waits for RAM.
j_random_hacker
Actually, it'd be faster if you used "i" instead of "i > 0" for your exit condition, and "--i" instead of "i--" (though the last one would probably be optimized by your compiler).
strager
@j_random_hacker, A better alternative is: int i = n; while(i --> 0) { }. I use this idiom at times where order of iteration is not important. (0 can be any number to terminate at.)
strager
+1  A: 

I'd prefer using < , since by just looking at the code you can tell its an increasing loop, it backs up the fact that you're using i++.

If you are using i++ and < and for some reason (other coder, typo, human mistake) your code changes the increment to i-- you'd instantly know that the loop isn't being evaluated, as with != it will work either way making it less trivial to debug.

Jj
Good observation; this has caught me a few times, and luckily I was using < instead of != so the loop didn't execute anything at all (which was easy to notice).
strager
A: 

I say it depends on the type of the iterator variable. If you know it's an integer, i would use the second, because you can say

Loop, as long as i is smaller than n

Which i think is easier to read for most programmers, including myself. If you don't know the type of the iterator variable, you should make as least assumptions about its capabilities as possible. The operator< may not be available for i: If it is any iterator other than a random access iterator, operator< is not guaranteed to be available. In this case i would use operator!=.

I would avoid preferring option < just because you could accidentally "step over" the end value. I think the argument is flawed. Because if you did accidentally step over, then that is a bug and it should be noticed as soon as possible (Fail-fast).

Johannes Schaub - litb