Break Statement

A break statement exits a loop immediately, regardless of its condition. Execution continues on the first line after the loop.

This page covers the break statement in the context of loops. For an introduction to loops, see Loop.

Breaking Out of a Loop#

The most common use is inside a while loop to stop based on something that happens inside the loop body, rather than the condition at the top:

while (true)
{
    string input = Console.ReadLine();
    if (input == "quit")
    {
        break;
    }
}

while (true) would run forever. The break exits the loop the moment the player types quit.

while True:
    user_input = input()
    if user_input == "quit":
        break
while (true) {
    let input = prompt();
    if (input === "quit") {
        break;
    }
}

Break in Other Contexts#

The break statement also works inside switch statements to exit a case block. The behaviour is the same — execution jumps to the first line after the enclosing block.

Common Mistakes#

Putting break outside a loop or switch

break only works inside a loop or a switch statement. Using it anywhere else is a compile error.

Breaking out of the wrong loop

In nested loops, break only exits the innermost loop it appears in. If you have a loop inside a loop and want to exit the outer one, a single break won’t do it — you need to restructure the logic or use a flag variable.

Expecting code after break to run

Any lines inside the loop body that come after break are unreachable — they will never execute. Move any cleanup or final output to after the closing } of the loop.

Resources#