Previous: 4.3.2 The break Statement
Up: 4.3 New Control Constructs
Previous Page: 4.3.2 The break Statement
Next Page: 4.4 Mixing Character and Numeric Input

4.3.3 The continue Statement

A continue statement also changes the normal flow of control in a loop. When a continue statement is executed in a loop, the current iteration of the loop body is aborted; however, control transfers to the loop condition test and normal loop processing continues, namely either a new iteration or a termination of the loop occurs based on the loop condition. As might be expected, the syntax of the continue statement is;

and the semantics are that statements in the loop body following the execution of the continue statement are not executed. Instead, control immediately transfers to the testing of the loop condition.

As an example, suppose we wish to write a loop to print out integers from 0 to 9, except for 5. We could use the continue statement as follows:

n = 0;
     while (n < 10) {
          if (n == 5) {
               n = n + 1;
               continue;
          }
          printf("Next allowed number is %d\n", n);
          n = n + 1;
     }
The loop executes normally except when n is 5. In that case, the if condition is True; n is incremented, and the continue statement is executed where control passes to the testing of the loop condition, (n < 10). Loop execution continues normally from this point. Except for 5, all values from 0 through 9 will be printed.

We can modify our previous text encryption algorithm (Figure 4.19) to ignore illegal characters in its input. Recall, in that task we processed characters one at a time, encrypting letters and passing all other characters as read. In this case we might consider non-printable characters other than white space to be typing errors which should be ignored and omitted from the output.

The code for the revised program is shown in Figure 4.23. We have used the function, illegal(), from the previous program (it is in chrutil.c) to detect illegal characters. When found, the continue statement will terminate the loop iteration, but continue processing the remaining characters in the input until EOF.

Sample Session:

It should be noted that the use of break and continue statements is not strictly necessary. Proper structuring of the program, using appropriate loop and if...else constructs, can produce the same effect. The break and continue statements are best used for ``unusual'' conditions that would make program logic clearer.



Previous: 4.3.2 The break Statement
Up: 4.3 New Control Constructs
Previous Page: 4.3.2 The break Statement
Next Page: 4.4 Mixing Character and Numeric Input

tep@wiliki.eng.hawaii.edu
Wed Aug 17 08:29:11 HST 1994