The content on this page is written in Chinese, and then traslated into English by machine. More accurate traslations are welcome at: https://github.com/wa-lang/man/tree/master/en

Ending's law: "Any application that can be compiled to WebAssembly, will be compiled to WebAssembly eventually."

4.6. switch statements

swtich statements are often used to replace multiple conditional statements. The general form is:

     switch InitialStatement, ConditionalExpression {
     case expression1:
         code block 1

     case expression2:
         code block 2

     default:
         default code block
     }

The switch statement will first execute the optional InitialStatement (the InitialStatement, can be omitted, which means there is no initial action), and then judge from top to bottom whether the value of the ConditionalExpression equals with a certain branch expression if equal, the code block of the corresponding branch will be executed; if all branch conditions are not met, the optional default code block will be executed (omitting the default branch means there is no default code block). For example:

func f(x: int) {
    switch x {
    case 0:
        println("x 为 0")

    case 1:
        println("x 为 1")

    default:
        println("x ==", x)
    }
}

Note that switch statements in Wa-lang languages ​​jump out by default: after entering a certain branch and executing the corresponding code block, the branch statement will jump out directly (that is, implicit break), which is opposite to the default behavior of C language.

Another special use of branch statements for type assertions will be described in Section 7.1.