jiafu
jiafu

Reputation: 6546

why not use < but != in loop for c++?

for (string::size_type ix = 0; ix != str.size(); ++ix)

why not use != instead of < in loop for C++?

Upvotes: 2

Views: 219

Answers (4)

Adrian Ratnapala
Adrian Ratnapala

Reputation: 5693

You can use either, and in C, I think < is more common. In C++, the STL adds a new twist:

for(FooType::iterator i = foo.begin(); i != foo.end(); i++)
    ... do stuff ...

Should use !=, because in some (most?) cases < will not even be defined for the iterator type. So you might want to use != in non-STL loops too, just for consistency.

Note: I normally use <, because as other answers say, it means you can't miss the sentry value. But this is no big deal; if you are unexpectedly missing the sentry, then you already have a bug.

Upvotes: 1

Mark Ransom
Mark Ransom

Reputation: 308206

The != idiom is necessary when you use iterators rather than integer indexes. If you often use iterators it just becomes habit.

Upvotes: 1

Sanish
Sanish

Reputation: 1719

why not use != instead of < in loop for C++?

Sometimes this will lead to some bugs hard to catch. If I want to print odd numbers below 10, then != is not the right choice. Following loop runs for ever.

for (int i=1; i!=10; i+=2)
{
     cout << i << endl;
}

Upvotes: 4

Niels Keurentjes
Niels Keurentjes

Reputation: 41958

It's a matter of preference mostly - the syntax is usually considered in human readable form to mean "while ix is not equal to (value) do (action) and keep incrementing ix". This is why it's often typed as != to directly 'translate' the "is not equal" consideration.

For most loops it doesn't matter which one you use, there is however the consideration that using < instead of != reduces the chance of overflow errors occurring, for example when using:

for(int i = 0; i != 25; i += 2)

While it is obvious in this case the loop will never terminate, if the 25 or 2 come from another source it might not be. Thus it's preferable to use < consistently as a precautionary habit.

Upvotes: 4

Related Questions