Control Flow Overview
WGSL provides structured, type-safe control flow statements for conditional branching and looping:
- If Statements: Standard conditional branching using
if,else ifchains, and an optionalelseblock. Parentheses around conditions are optional, but curly braces{}are strictly required around block bodies. All guard conditions must evaluate to a strictbooltype, as WGSL does not support implicit type coercion. - Switch Statements: Multi-way branching evaluated against discrete, concrete integer scalar values (such as
i32oru32). Everyswitchstatement requires adefaultblock, and all cases must have curly braces{}. WGSL does not support implicitfallthrough, but allows sharing code blocks by listing multiple comma-separated case selectors. - While Statements: Standard pre-checked loop constructs that repeatedly execute a body as long as a boolean guard condition remains
true. Parentheses around conditions are optional, but curly braces{}are strictly required around the loop body. - For Statements: Iterative loops containing an optional initializer, loop guard condition, and increment/update expression, separated by semicolons. WGSL does not support post-increment/decrement operators (
++/--) or compound assignments (like+=) as loop updates; they must be written as explicit assignments (e.g.,i = i + 1). - The loop Statement: WGSL's fundamental loop construct that executes indefinitely unless explicitly exited via
break,return, or abreak ifstatement inside an optionalcontinuingblock. It serves as the primitive building block that other loops are compiled into, and can be used to construct custom structures likedo-whileordo-untilloops.