Here's another answer that no one seems to have come up with yet.
for loops should be used when you need to iterate over a sequence. Using
!= is the most concise method of stating the terminating condition for the loop. However, using a less restrictive operator is a very common defensive programming idiom. For integers it doesn't matter - it is just a personal choice without a more specific example. Looping over collections with iterators you want to use
!= for the reasons that others have stated. If you consider sequences of
double, then you want to avoid
!= at all costs.
What I wanted to point out is that
for is used when you need to iterate over a sequence. The generated sequence has a starting point, an interval, and a terminating condition. These are concisely specified within the
for statement. If you find yourself either (1) not including the step portion of the
for or (2) specifying something like
true as the guard condition, then you should not be using a
while loop is used to continue processing while a specific condition is met. If you are not processing a sequence, then you probably want a
while loop instead. The guard condition arguments are similar here, but the decision between a
while and a
for loop should be a very conscious one. The
while loop is under-appreciated in C++ circles IMO.
If you are processing a collection of items (a very common
for-loop usage), then you really should use a more specialized method. Unfortunately,
std::for_each is pretty painful in C++ for a number of reasons. In many cases separating the body of a
for loop in a free-standing function (while somewhat painful) results in a much cleaner solution. When working with collections, consider
std::accumulate. The implementation of many algorithms become concise and crystal clear when expressed in this manner. Not to mention that isolating the body of the loop into a separate function/method forces you to concentrate on the algorithm, its input requirements, and results.
If you are using Java, Python, Ruby, or even C++0x, then you should be using a proper collection foreach loop. As C++ compilers implement this feature, a number of
for loops will disappear as will these types of discussions.