Guideline: while vs for

c++, coding-style

Solution

Not all loops are for iteration:

while(condition) // read e.g.: while condition holds
{
}

is ok, while this feels forced:

for(;condition;)
{
}

You often see this for any input sources.

You might also have implicit iteration:

while(obj.advance())
{
}

Again, it looks forced with for.

Additionally, when forcing `for` instead of `while`, people tend to misuse it:

for(A a(0); foo.valid(); b+=x); // a and b don't relate to loop-control

Problem

Disclaimer: I tried to search for similar question, however this returned about every C++ question... Also I would be grateful to anyone that could suggest a better title. There are two eminent loop structure in C++: `while` and `for`. - I purposefully ignore the `do ... while` construct, it is kind of unparalleled - I know of `std::for_each` and `BOOST_FOREACH`, but not every loop is a `for each` Now, I may be a bit tight, but it always itches me to correct code like this: ``` int i = 0; while ( i < 5) { // do stuff ++i; // I'm kind and use prefix notation... though I usually witness postfix } ``` And transform it in: ``` for (int i = 0; i < 5; ++i) { // do stuff } ``` The advantages of `for` in this example are multiple, in my opinion: - Locality: the variable i only lives in the scope of the loop - Pack: the loop 'control' is packed, so with only looking at the loop declaration I can figure if it is correctly formed (and will terminate...), assuming of course that the loop variable is not further modified within the body - It may be inlined, though I would not always advised it (that makes for tricky bugs) I have a tendency therefore not to use `while`, except perhaps for the `while(true)` idiom but that's not something I have used in a while (pun intended). Even for complicated conditions I tend to stick to a `for` construct, though on multiple lines: ``` // I am also a fan of typedefs for (const_iterator it = myVector.begin(), end = myVector.end(); it != end && isValid(*it); ++it) { /* do stuff */ } ``` You could do this with a `while`, of course, but then (1) and (2) would not be verified. I would like to avoid 'subjective' remarks (of the kind "I like for/while better") and I am definitely interested to references to existing coding guidelines / coding standards. EDIT: I tend to really stick to (1) and (2) as far as possible, (1) because locality is recommended >> C++ Coding Standards: Item 18, and (2) because it makes maintenance easier if I don't have to scan a whole body loop to look for possible alterations of the control variable (which I takes for granted using a `for` when the 3rd expression references the loop variables). However, as `gf` showed below, while do have its use: ``` while (obj.advance()) {} ``` Note that this is not a rant against `while` but rather an attempt to find which one of `while` or `for` use depending on the case at hand (and for sound reasons, not merely liking).

Original source