Reputation: 9035
Given a vector v
, I want to loop through each element in the vector and perform an operation that requires the current index.
I've seen a basic for loop written both of these ways:
// Using "<" in the terminating condition
for (auto i = 0; i < v.size(); ++i)
{
// Do something with v[i]
}
// Using "!=" in the terminating condition
for (auto i = 0; i != v.size(); ++i)
{
// Do something with v[i]
}
Is there any practical reason to prefer one over the other? I've seen it written using <
much more often, but is there a performance benefit to using !=
?
Upvotes: 0
Views: 203
Reputation: 142218
There is no difference in performance.
There is a huge difference if you decided to change ++i
in such a way that the loop would step over the desired end.
For clarity for other programmers reading your code, use the convention they expect to see, namely <
. When I see i != ...
, I think "he is skipping over that one value".
The is an obscure bug with <
-- Suppose you iterating over all 256 chars
using a byte-sized i
. The value will overflow and probably never show the value 256
. The loop will never stop. And !=
won't fix the bug.
Upvotes: 0
Reputation: 9540
There is one, albeit kinda convoluted, reason to prefer <
over !=
.
If for whatever reason the body of your lop modifies i
and skips over the threshold, <
still terminates the loop, where !=
will keep iterating.
It might make no difference in the vast majority of cases, but getting used to <
might prevent bugs that !=
won't. There's also an additional advantage, that is ridiculously minor but <
takes less characters to write, so it makes the source file smaller.
Again the above argument is borderline a joke, but if you need an argument to use one over the other, there you have it.
Upvotes: 1
Reputation: 238311
You should probably prefer using a range-for instead.
Is there any practical reason to prefer one over the other?
There are no strong reasons to prefer one way or another given that both have equivalent behaviour.
Using the less than operator works even if the end condition is not one of the values of the accumulator which would be possible if increment was greater than 1 or the initial value was greater than the end condition. As such, it is more general, which means that using it always may be more consistent. Consistency is a weak argument, but a weak argument is better than no argument if you agree with it.
Upvotes: 0