The continue statement tells the interpreter to immediately start the next iteration of the loop and skip the remaining code block. When a continue statement is encountered, the program flow moves to the loop check expression immediately and if the condition remains true, then it starts the next iteration, otherwise the control comes out of the loop.
The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.
The continue statement (with or without a label reference) can only be used to skip one loop iteration.
The difference between continue and the break statement, is instead of “jumping out” of a loop, the continue statement “jumps over” one iteration in the loop.
However, when the continue statement is executed, it behaves differently for different types of loops:
- In a while loop, the condition is tested, and if it is true, the loop is executed again
- In a for loop, the increment expression (e.g. i++) is first evaluated, and then the condition is tested to find out if another iteration should be done
The continue statement can also be used with an optional label reference.
The example below illustrates the use of a continue statement with a while loop. Notice how the continue statement is used to skip printing when the index held in variable x reaches 5