break

Summary

Exits the current loop, switch case or default clause, or labeled statement. Program will continue executing from the statement following the exited statement.

Syntax

break [label];

Parameters

label
The label associated with a statement or loop. If the break statement does not occur inside a switch statement or loop, the label is required.

Description

break can only be used inside loops, switch statements, and labeled statements. It will cause the current loop, switch case or default clause, or labeled statement to terminate execution and continue execution from the statement immediately following the terminated statement.

Usage inside Loops

In its simplest form, the break statement will terminate the nearest loop:

1
2
3
4
5
6
7
8
9
while (true) {
    break; // terminate loop
}
 
for (int i = 0; i < 5; ++i) {
    if (i == 3) {
        break; // terminate loop
    }
}

Inside nested loops, the nearest loop enclosing the break statement will be exited. For instance:

1
2
3
4
5
6
7
for (int x = 0; x < 5; ++x) {
    for (int y = 0; y < 5; ++y) {
        break; // terminates the loop iterating over 'y'
    }
     
    break; // terminates the loop iterating over 'x'
}

In order to exit the outer loop from the inner loop in the above example, we would have to use labels. If we label the loops, we can refer to the outer loop explicitly from the break statement:

1
2
3
4
5
outerLoop: for (int x = 0; x < 5; ++x) {
    innerLoop: for (int y = 0; y < 5; ++y) {
        break outerLoop; // terminates the loop iterating over 'x'
    }
}

Usage inside Switch Statements

break can be used inside the case or default clauses of a switch statement. In fact, a break statement is expected in each case and default clause to prevent "switch fallthrough." If a break statement is not inserted in a case or default clause, the compiler will raise a warning at compile time.Unimplemented

In the following sample, notice how we insert a break statement for each case and default clause of the switch statement:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int x = 1;
switch(x) {
    case 1:
        Console.log("Value is 1");
        break;
    case 2:
        Console.log("Value is 2");
        break;
    case 3:
        Console.log("Value is 3");
        break;
    default:
        Console.log("Value is not 1, 2, or 3");
        break;
}

The break statement prevents the case or default clause from moving to the next matching clause. For more information on switch fallthrough and the usage of break inside switch statements, refer to the switch statement documentation.

Differences to JavaScript

break can be used inside labeled statements without explicitly providing the label to break from.

1
2
3
4
mylabel: break;
mylabel: {
    break;
}

See Also

Share

HTML | BBCode | Direct Link