‘<' versus '!=' as condition in a 'for' loop

syntax

Say you have the following forloop*:

for (int i = 0; i < 10; ++i) {
    // ...
}

which it could commonly also be written as:

for (int i = 0; i != 10; ++i) {
    // ...
}

The end results are the same, so are there any real arguments for using one over the other? Personally I use the former in case i for some reason goes haywire and skips the value 10.

* Excuse the usage of magic numbers, but it's just an example.

Best Answer

The reason to choose one or the other is because of intent and as a result of this, it increases readability.

Intent: the loop should run for as long as i is smaller than 10, not for as long as i is not equal to 10. Even though the latter may be the same in this particular case, it's not what you mean, so it shouldn't be written like that.

Readability: a result of writing down what you mean is that it's also easier to understand. For example, if you use i != 10, someone reading the code may wonder whether inside the loop there is some way i could become bigger than 10 and that the loop should continue (btw: it's bad style to mess with the iterator somewhere else than in the head of the for-statement, but that doesn't mean people don't do it and as a result maintainers expect it).

Related Topic