if and else in WebAssembly
Branches are typed: a result-carrying if must fill both arms.
(module
;; if is typed: (result i32) says both branches leave one value.
(func (export "abs") (param $n i32) (result i32)
(if (result i32)
(i32.lt_s (local.get $n) (i32.const 0))
(then (i32.sub (i32.const 0) (local.get $n)))
(else (local.get $n))))
;; Without a result type, if is a statement and else may vanish.
(func (export "cap_at_ten") (param $n i32) (result i32)
(if (i32.gt_s (local.get $n) (i32.const 10))
(then (return (i32.const 10))))
(local.get $n)))
How it works
(if (result i32) ...)promises one value from either branch.(then ...)and(else ...)each leave that value.- A statement if may skip else;
returnexits the whole function.
Keywords and builtins used here
elseexportfunci32ifmoduleparamresultreturnthen
The run, in numbers
- Lines
- 13
- Characters to type
- 464
- Tokens
- 108
- Three-star pace
- 65 tpm
At the three-star pace of 65 tokens a minute, this run takes about 100 seconds.
Step 1 of 3 in Control flow, step 10 of 28 in Language basics.