This C# statement alters control flow. It is used in loop bodies. It allows you to skip the execution of the rest of the iteration.
With the continue statement, we jump immediately to the next iteration in the loop. This keyword is often useful in while
-loops, but can be used in any loop.
This program uses the continue statement. In a while-true
loop, the loop continues infinitely. We call Sleep()
to make the program easier to watch as it executes.
using System; using System.Threading; class Program { static void Main() { int value = 0; while (true) { // Part 1: increment number. value++; // Part 2: if number is 3, skip the rest of this loop iteration. if (value == 3) { continue; } Console.WriteLine(value); // Pause. Thread.Sleep(100); } } }1 2 4 5...
We must use a continue statement within a loop. We get an error from the compiler if no enclosing loop is found. The same restriction applies to break
.
class Program { static void Main() { continue; } }Error CS0139 No enclosing loop out of which to break or continue
The C# language is a high-level language. When it is compiled, it is flattened into a sequence of instructions. These are intermediate language opcodes.
In branch statements, a condition is tested. And based on whether the condition is true, the runtime jumps to another instruction in the sequence.
The continue statement exits a single iteration of a loop. It does not terminate the enclosing loop entirely or leave the enclosing function body.
Continue is often most useful in while or do-while
loops. For
-loops, with well-defined exit conditions, may not benefit as much.