Skip to content

Control Flow

Apoorv Singal edited this page Aug 30, 2020 · 3 revisions

Control flow of volant code is managed using if-else statements, switch statements, and loops.

If-else statement

if [optional statement;] <condition> {
  <statements>
} else if <condition> {
    <statements>
} else {
    <statements>
}

You can chain as many else if blocks as you want.

Example:


func main() {
    if i := 0; i == 3 {
        io.println("i is three."); // doesn't get printed
    } else if i == 2 {
        io.println("i is two."); // doesn't get printed
    } else if i == 0 {
        io.println("i is zero."); // gets printed
    } else {
        io.println("i is not 0, 1, 2 or 3."); // doesn't get printed
    }
    return 0;
}

Switch Statement

switch [optional statement;] [optional expression] {
case value1:
    // do stuff
    break;
case value2:
    // do stuff
    break;
default:
    // so stuff
    break
}

Switch statements in Volant work just like c switch statements with few minor changes. Users can provide an optional statement to the switch which is executed right before executing the switch expression and users can omit the switch expression which is the same as doing switch true {...}. Example:

switch {
case true:
    io.println("I will be printed");
    break;
case false:
    io.println("I won't be printed");
    break;
}

switch x := 0; x {
case 0:
    io.println("I will be printed");
    break;
case 1:
    io.println("I won't be printed");
    break;
}

Loops

for [optional statement;][optional condition [;optional statement]] { 
    // do stuff
}

Example:

for i := 0; i < 100; ++i { // good old c-style for loop
    // do stuff
}

for i := 0; i < 100 { // omit loop statement and semicolon
    // do stuff
}

i := 0
for i < 100 { // use for loop as while loop
    // do stuff
    ++i;
}

for { // create an infinite loop
    // do stuff
}

break and continue work just like c.

Clone this wiki locally