Mostly Harmless

Switch statement

From Unreal Wiki, The Unreal Engine Documentation Site
Jump to: navigation, search

The switch statement is used to conditionally execute code, much like the If statement.

Syntax[edit]

The general syntax of the switch statement is as follows:

switch (expression) {
  case expression:
    ...
    break;
  
  case expression:
    ...
  
  default:
    ...
}

When code execution reaches a switch statement, it first evaluates the expression in parentheses after the "switch" keyword. Unlike the If statement's condition, this expression does not have to evaluate to a value of type bool, but can be of any supported UnrealScript type. Then the engine checks all case labels in the order they occur. Case expressions must have the same result type as the switch expression. If a case expression evaluates to the same value as the switch expression, the case's code is executed, otherwise the next case expression is checked. The default label must be the last case in the switch block, but can be omitted.

You can use the break statement to exit the switch block at any given point except inside an if block. Execution will continue at the first statement after the closing curly brace of the switch block.

Note: By default code execution will "fall through" to the next case if you don't use a break statement. When execution falls though, the case expression is still evaluated, but its result is ignored. Putting a break as the last statement on the last case is optional.