Control Flow

6.1 Structured Blocks

block... end A label at the end. br to it jumps forward (break).

loop... end A label at the start. br to it jumps backward (continue).

if... else... end Conditional (pops an i32 condition) Unconditional branch to label L Branch if the top value is non-zero br_table L0 L1... Ldefault Jump table (switch) Return from the function

call f, call_indirect, call_ref, return_call* Function calls (Module 9, 25)

6.2 Examples

Labels are referenced by name or by relative depth (br 0 targets the innermost block).

Blocks can take parameters and return multiple results (multi-value): (block (param i32) (result i32 i32) ...).

;; if/else with results
(func $max (param $a i32) (param $b i32) (result i32)
  (if (result i32) (i32.gt_s (local.get $a) (local.get $b))
    (then (local.get $a))
    (else (local.get $b))))

;; while loop: count down
(func $countdown (param $n i32)
  (block $exit
    (loop $top
      (br_if $exit (i32.eqz (local.get $n)))
      ;; ... body ...
      (local.set $n (i32.sub (local.get $n) (i32.const 1)))
      (br $top))))

;; switch with br_table
(func $classify (param $x i32) (result i32)
  (block $default
    (block $two
      (block $one
        (block $zero
          (br_table $zero $one $two $default (local.get $x)))
        (return (i32.const 100)))    ;; case 0
      (return (i32.const 200)))      ;; case 1
    (return (i32.const 300)))        ;; case 2
  (i32.const -1))                    ;; default