LEVIATHAN v962456e · 962456eee1

Statements

break and continue

Leaving a loop early or skipping to its next iteration, and what counts as a loop for these statements.

since 0.1.0-alpha.1linuxwindowswasm

Description

break; exits the nearest enclosing loop: a while, a do-while, a C-style for, or a for-in.

continue; skips the rest of the current iteration and goes on to the next one. What "next" means depends on the loop:

  • in while and do-while, control goes to the condition;
  • in a C-style for, control goes to the step expression, then to the condition;
  • in for-in, control goes to the next element.

do stmt while (cond); runs its body once unconditionally and then repeats while cond holds, so, unlike while, it tests after the body. A continue inside a do body jumps to that test, not back to the top of the body.

break and continue in each kind of loop

for (int i = 0; i < 6; i = i + 1) {
    if (i == 1) continue;
    if (i == 4) break;
    console.write("${i}");
}
console.writeln("");

int n = 0;
do {
    n = n + 1;
    if (n == 2) continue;
    console.write("d${n}");
} while (n < 4);
console.writeln("");

for (int v in 1..5) {
    match (v) {
        2 => { continue; }
        4 => { break; }
        else => console.write("v${v}");
    }
}
console.writeln("");
023
d1d3d4
v1v3

Rules

  • break and continue outside any loop are compile errors ('break' outside a loop).
  • A lambda body is its own loop scope. A bare break or continue inside a lambda never reaches a loop of the enclosing function; it is legal only if the lambda's own body contains a loop around it.
  • match is not a loop boundary. A break or continue inside a match arm that sits inside a loop applies to that loop, not to the match.
  • Both statements accept a label to name an outer loop. See lang.labeled-loops.

Examples

A lambda has its own loop scope

void f() {
    for (int i = 0; i < 3; i = i + 1) {
        var each = (x) => {
            for (int j = 0; j < 5; j = j + 1) {
                if (j == x) break;
                console.write("j${j}");
            }
        };
        each(i);
    }
    console.writeln("");
}
f();
j0j0j1
void f() { break; }
// error: 'break' outside a loop

void g() { continue; }
// error: 'continue' outside a loop
not run — shows a compile error

Notes

The break in the lambda above ends the lambda's own inner loop. The outer for is not affected.

See also

  • Array — An ordered sequence of values of one type, Array<T>, with value semantics.