Lyricdev
GitHub

LYR-SEM0148

a 'break' with a value out of a 'while' or 'for'

error · spec 07-statements

A 'break' carries a value, and the loop it leaves is a 'while' or a 'for', not a 'loop'.

Explanation

Only loop { … } is an expression with a value: it ends through a break alone, so every way out can carry one. A while or a for also ends when its condition or its source does, and there would be no value then.

Use return in a function, store the value in a variable before break, or write the loop as loop { … }.

Wrong

fn firstPositive(xs: int[]): int {
    var i = 0;
    while (i < xs.length()) {
        if (xs[i] > 0) { break xs[i]; }
        i += 1;
    }
    return 0;
}

fn main(): void {
    let _ = firstPositive([0, 3]);
}
fn firstPositive(xs: int[]): int {
    var i = 0;
    while (i < xs.length()) {
        if (xs[i] > 0) { return xs[i]; }
        i += 1;
    }
    return 0;
}

fn main(): void {
    let _ = firstPositive([0, 3]);
}