#10. Choosing the right loop structure

C++ has three loop instructions: for, while and do ... while. To choose wisely among them, you need to know what their differences are.

1) for

for loop makes sense when you repeat an action for a known number of times, or for all the elements of a known set.

This is the syntax of a for loop:

for (initialization; condition; expression)
{
    statement
}

statement is actually a compound statement, that is, a block of code. This is called the body of the loop. In contrast, the initialization, condition and expression together are called the header of the loop. The initialization is a single statement which ends at the semicolon I wrote after it. The condition is a boolean expression. The expression is a statement. It should be a single statement which modifies one variable which is involved in the condition (see #guideline #5).

The initialization is performed. Then, the condition is evaluated. Then, two things can happen. If the condition is false, the code jumps right after the for statement block. If instead it is true, the statement (the loop body) is executed. After it, the incrementing expression is evaluated. And then, again, the condition is evaluated. This sequence of actions is repeated, until the condition is evaluated to false.

Note that a new form of for loop, the range-based for, is available since versiĆ³n C++11 of standard of the C++ language. I will cover it in a separate guideline, to keep this introduction simple.

2) while

This is the syntax of a while loop:

while (condition)
{
    statement
}

If you don't know the number of times or the total set of elements for which you're going to do something, you'd better chose one of the other two looping structures: a while or a do ... while.

while loop checks its condition first and, if it is true, it executes its statements. Thus, it may never perform the repeated action (if the condition happens to be false at the beginning).

3) do ... while

This is the syntax of a do...while loop:

do
{
    statement
} while (condition);

do ... while loop executes the repeated action at least once and then checks the condition to see if it must keep repeating it, or just finish. So it is useful when you know you need to execute the actions in the statements once, and only after that check the loop condition.

See also

Bibliography

[McConnell 2004]
Steve McConnell: Code Complete, 2nd Edition, Microsoft Press, 2004.

This book discusses loops in Chapter 16: "Loops" (pages 367-389).

Comments

Popular posts from this blog

#13. Organize your code in classes

#2. Make all type conversions explicit