Code Complete 2 – Steve McConnell – Controlling Loops

I just love Steve McConnell's classic book Code Complete 2, and I recommend it to everyone in the Software 'world' who's willing to progress and sharpen his skills.

Other blog posts in this series:

"Loop" is a structure that causes a program to repeatedly execute a block of code. Common loop types are for, while, and do-while.

When to use the while loop

If you don't know ahead of time exactly how many times you'll want the loop to iterate, use the while loop. Contrary to what some novices think, the test for the loop exit is performed only once each time through the loop, and the main issue concerning while loop is deciding whether to test at the beginning or the end of the loop.

  • while - loop tests condition at the beginning
  • do-while - tests condition at the end, which means that the body of the loop gets executed at least once.
  • loop-with-exit - structure more closely models human thinking. This is the loop in which the exit condition appears in the middle of the loop rather than at the beginning or the end.

When to use the for loop

A for loop is a good choice when you need a loop that executes a specified number of times. If you have a condition under which execution has to jump out of a loop, use a while loop instead.

When to use the foreach loop

It is useful for performing an operation on each member of an array or some other container. It has an advantage of eliminating loop-housekeeping arithmetic and therefore eliminating any chance of errors in the loop-housekeeping arithmetic.

Controlling the loop

You can use two practices. First, minimize the number of factors that affect the loop. Simplify! Simplify! Simplify! Second, treat the inside of the loop as if it were a routine-keep as much control as possible outside the loop.

Entering the loop

  • Enter the loop from one location only
  • Put initialization code directly before the loop - Principle of Proximity advocates putting related statements together.
  • Use while ( true ) for infinite loops - that's considered a standard way of writing an infinite loop in C++, Java, Visual Basic, and other languages. for(;;) is an accepted alternative.

Processing the middle of the loop

  • Use { and } to enclose the statements in a loop - Use brackets every time. They don't cost anything in speed or space at runtime, they help readability, and they help prevent errors as the code is modified.
  • Avoid empty loops - In C++ and Java, it's possible to create an empty loop, one in which the work the loop is doing is coded on the same line as the test that checks whether the work is finished. Here's an example:
    while( (inputChar = dataFile.GetChar() ) != CharType_Eof ) {

    The loop would be much clearer if it were recoded so that the work it does is evident to the reader:

    do {
        inputChar = dataFile.GetChar();
    } while ( inputChar != CharType_Eof );

The new code takes up three full lines rather than that of one line, which is appropriate since it does the work of three lines rather than that of one line.
+ Keep loop-housekeeping chores at either the beginning or the end of the loop - As a general rule, the variables you initialize before the loop are the variables you'll manipulate in the housekeeping part of the loop.

Exiting the loop

  • Assure that the loop ends
  • Don't monkey with the loop index of a for loop to make the loop terminate
  • Avoid code that depends on the loop index's final value

Exiting loops early

The break statement causes a loop to terminate through the normal exit channel; the program resumes execution at the first statement following the loop.

continue causes the program to skip the loop body and continue executing at the beginning of the next iteration of the loop.

Inefficient programmers tend to experiment randomly until they find a combination that seems to work. If a loop isn't working the way it's supposed to; the inefficient programmer changes the < sign to a <= sign. If that fails, the inefficient programmer changes the loop index by adding or subtracting 1. Eventually, the programmer using this approach might stumble onto the right combination or simply replace the original error with a more subtle one. Even if this random process results in a correct program, it doesn't result in the programmer's knowing why the program is correct.

How long should a loop be?

Make your loops short enough to view all at once. Experts have suggested a loop-length limit of one page (about 50 lines of code). When you begin to appreciate the principle of writing simple code, however, you'll rarely write loops longer than 15 or 20 lines.

Creating loops easily - from the inside out

If you sometimes have trouble coding a complex loop, which most programmers do, you can use a simple technique to get it right the first time.

Here's the general process:
+ Start with one case.
+ Code that case with literals.
+ Then indent it, put a loop around it, and replace the literals with loop indexes or computed expressions.
+ Put another loop around that, if necessary, and replace more literals.
+ Continue the process as long as you have to
+ When you finish, add all the necessary initializations.

Since you start at the simple case and work outward to generalize it, you might think of this as coding from the inside out.

Written by Nikola Brežnjak