Skip to content

Control Flow

Overview

Control flow statements alter the sequential execution of program statements.

Syntax

if (cond) {
    doSomething();
} else if (cond2) {
    doOtherThing();
} else {
    doFallback();
}

while (cond) {
    doWork();
}

break;

continue;

return 123;

Rules

Condition Types

The condition expression MUST be convertible to bool. All integer types MUST be convertible to bool where zero evaluates to false and non-zero evaluates to true. Struct handles (&T) MUST be convertible to bool where null evaluates to false and non-null evaluates to true. Slice handles ([]T) MUST NOT be convertible to bool; use the length operator # to check for empty slices.

If Statement

The if statement evaluates the condition and executes the appropriate branch. An if statement without an else clause MAY be followed by an else if clause. else if chains MUST be supported as a single syntactic form. An else clause MUST be associated with a directly preceding if without an else.

While Statement

The while statement MUST evaluate the condition, if true, the body MUST be executed, after the body is executed the sequence MUST repeat until the condition returns false. If false, execution MUST continue from directly after the loop.

Break Statement

break MUST only appear inside a while loop. break MUST terminate the nearest enclosing while loop and continue execution on the first statement after the loop.

Continue Statement

continue MUST only appear inside a while loop. continue MUST skip to the next condition evaluation of the nearest enclosing while loop.

Return Statement

A function that declares a return type MUST return a value of that type on all code paths that reach the end of the function's execution. A return statement without an expression MUST only be allowed in functions which don't have a return type.

Flow-Sensitive Promotion

When a handle (type &T) is used as the condition of an if statement, the compiler MUST track it as known-non-null in all code paths where non-nullness can be statically guaranteed. For example, when the consequent of if (!h) terminates via return or break, the handle MUST be tracked as known-non-null in all subsequent statements in the enclosing scope after the if statement as well as in the else block. The compiler MAY include additional static tracking of handle validity.

Block Semantics

All bodies of control structures MUST be non-empty braced blocks. The last statement in a block MUST be followed by a semicolon. All statements in blocks MUST be followed by a semicolon.