Node:Continue Statement, Next:, Previous:Break Statement, Up:Statements



The continue Statement

As with break, the continue statement is used only inside for, while, and do loops. It skips over the rest of the loop body, causing the next cycle around the loop to begin immediately. Contrast this with break, which jumps out of the loop altogether.

The continue statement in a for loop directs awk to skip the rest of the body of the loop and resume execution with the increment-expression of the for statement. The following program illustrates this fact:

BEGIN {
     for (x = 0; x <= 20; x++) {
         if (x == 5)
             continue
         printf "%d ", x
     }
     print ""
}

This program prints all the numbers from 0 to 20--except for 5, for which the printf is skipped. Because the increment x++ is not skipped, x does not remain stuck at 5. Contrast the for loop from the previous example with the following while loop:

BEGIN {
     x = 0
     while (x <= 20) {
         if (x == 5)
             continue
         printf "%d ", x
         x++
     }
     print ""
}

This program loops forever once x reaches 5.

The continue statement has no meaning when used outside the body of a loop. Historical versions of awk treated a continue statement outside a loop the same way they treated a break statement outside a loop: as if it were a next statement (see The next Statement). Recent versions of Unix awk no longer work this way, and gawk allows it only if --traditional is specified on the command line (see Command-Line Options). Just like the break statement, the POSIX standard specifies that continue should only be used inside the body of a loop. (d.c.)