Skip to content

Latest commit

 

History

History
41 lines (33 loc) · 735 Bytes

File metadata and controls

41 lines (33 loc) · 735 Bytes

Break

While loops will usually stop running when the condition at the top evaluates to false.

This can be bypassed by using the break statement.

~void main() {
int x = 5;
while (x > 0) {
    if (x == 2) {
        break;
    }
    x--;
}

IO.println(
    "Final value of x is " + x
);
~}

If a break is reached, the code in the loop stops running immediately. The condition of the loop is not checked again.

This can be useful in a variety of situations, but notably it is the only way to exit from an otherwise endless loop.

~void main() {
while (true) {
    IO.println(
        "The people started singing it not knowing what it was"
    );

    // Will immediately leave the loop
    break;
}
~}