Switch statement


In computer programming, a switch statement is a selection control flow mechanism that changes execution control based on the value of an expression. A switch statement is similar to an if statement but instead of branching only on true or false, it branches on any number of values. Although the syntax varies by programming language, most imperative languages provide a statement with the semantics described here as the switch statement. Often denoted with the keyword, some languages use variations such as,, or.

Value

Sometimes, use of a switch statement is considered superior to an equivalent series of if-then-else statements because it is:
; Easier to understand: And consequently easier to maintain: at least partially since it's fixed depth.
; Easier to debug: For example, setting breakpoints on code vs. a call table, if the debugger has no conditional breakpoint capability.
; Easier to verify: that all values are handled since a compiler can warn if a value is not handled.
; Can execute faster: An optimized implementation may execute much faster because it is often implemented as a branch table. When implemented as such, a switch statement embodies a perfect hash.
; Less complex: In terms of a control-flow graph, a switch statement consists of two nodes, plus one edge between them for each option. By contrast, a sequence of if-then-else statements has an additional node for every case other than the first and last, together with a corresponding edge. The resulting control-flow graph for the sequences of "if"s thus has many more nodes and almost twice as many edges, without adding useful information.

Elements

Typically, a switch statement involves:
; Verb: Starts with a control verb such as which is followed by an expression which is often a variable name; the control expression or control variable.
; Cases: Subsequent branch alternative sections each start with a keyword plus a value along with code to execute for the value. In some languages, i.e. PL/I and Rexx, if the control expression is omitted then each alternative begins with a clause containing a Boolean expression and a match occurs for the first case for which that expression evaluates true; similar to an if-then-else structure.
; Default: An optional default case is typically allowed, often via a keyword such as,, or. Control branches to this section when none of the other cases match the control expression. In some languages, such as C, if no case matches and the default section is omitted, the statement does nothing, but in others, like PL/I, an error occurs.

Fall through

Two main variations of the switch statement include unstructured which supports fall through and structured which does not.
For a structured switch, as in Pascal-like languages, control jumps from the start of the switch statement to the selected case and at the end of the case, control jumps to the end of the switch statement. This behaves like an if–then–else conditional but supports branching on more than just true and false values. To allow multiple values to execute the same code, the syntax permits multiple values per case.
An unstructured switch, as in C, acts like goto. Control branches from the start of the switch to a case section and then control continues until either a block exit statement or the end of the switch statement. When control branches to one case, but continues into the subsequent branch, the control flow is called fall through, and allows branching to the same code for multiple values.
Fall through is prevented by ending a case with a keyword, but a common mistake is to accidentally omit the keyword, causing unintentional fall through and often a bug. Therefore, many consider this language feature to be dangerous, and often fall through code results in a warning from a code quality tool such as lint.
Some languages, such as JavaScript, retain fall through semantics, while others exclude or restrict it. Notably, in C# all blocks must be terminated with or unless the block is empty which limits fall through only for branching from multiple values.
In some cases, languages provide optional fall through. For example, Perl does not fall through by default, but a case may explicitly do so using a keyword, preventing unintentional fall through. Similarly, Bash defaults to not falling through when terminated with, but allows fall through with or instead.
An example of a switch statement that relies on fall through is Duff's device.

Case expression evaluation

Some languages allow for a complex case expression, allowing for more dynamic branching behavior. This prohibits certain compiler optimizations, so is more common in dynamic languages where flexibility is prioritized over performance.
For example, in PHP and Ruby, a constant can be used as the control expression, and the first case statement that evaluates to match that constant is executed. In the following PHP code, the switch expression is simply the true value, so the first case expression that is true is the one selected.

switch

This feature is also useful for checking multiple variables against one value rather than one variable against many values.

switch

COBOL also supports this form via its EVALUATE statement. PL/I supports similar behavior by omitting the control expression, and the first WHEN expression that evaluates as true is executed.
In Ruby, due to its handling of equality, the case expression can be used to test a variable's class. For example:

case input
when Array then puts 'input is an Array!'
when Hash then puts 'input is a Hash!'
end

Result value

Some languages support evaluating a switch statement to a value.

Case expression

The case expression is supported by languages dating at least as far back as ALGOL-W. In ALGOL-W, an integer expression was evaluated, which then evaluated the desired expression from a list of expressions:

J := case I of ;
A := case DECODE-128 of ;

Other languages supporting the case expression include SQL, Standard ML, Haskell, Common LISP, and Oxygene.

Switch expression

The switch expression evaluates to a value. There is also a new form of case label, where the right-hand-side is a single expression. This also prevents fall through and requires that cases are exhaustive. In Java SE 13 the yield statement is introduced, and in Java SE 14 switch expressions become a standard language feature. For example:

int ndays = switch ;

Ruby also supports these semantics. For example:

catfood =
case
when cat.age <= 1
junior
when cat.age > 10
senior
else
normal
end

Exception handling

A number of languages implement a form of switch statement in exception handling, where if an exception is raised in a block, a separate branch is chosen, depending on the exception. In some cases a default branch, if no exception is raised, is also present. An early example is Modula-3, which use the TRY...EXCEPT syntax, where each EXCEPT defines a case. This is also found in Delphi, Scala, and Visual Basic.NET.

Examples

C

The following code is a switch statement in C. If is 1, it outputs "You're one.". If is 3, it outputs "You're three. You're three or four.".

switch

Python

Python supports the and keywords. It doesn't allow fall through. Unlike if statement conditions, the keyword cannot be used to differentiate between cases. is equivalent to in C.

letter = input.strip.casefold
match letter:
case "a" | "e" | "i" | "o" | "u":
print
case "y":
print
case _:
print

Pascal

The following is an example in Pascal:

case someChar of
'a': actionOnA;
'x': actionOnX;
'y','z':actionOnYandZ;
else actionOnNoMatch;
end;

In the Oxygene dialect of Pascal, a switch statement can be used as an expression:

var i : Integer := case someChar of
'a': 10;
'x': 20;
'y': 30;
else -1;
end;

Shell script

The following is an example in Shell script:

case $someChar in
a) actionOnA; ;;
x) actionOnX; ;;
) actionOnYandZ; ;;
*) actionOnNoMatch ;;
esac

Assembler

A switch statement in assembly language:

switch:
cmp ah, 00h
je a
cmp ah, 01h
je b
jmp swtend ; No cases match or "default" code here
a:
push ah
mov al, 'a'
mov ah, 0Eh
mov bh, 00h
int 10h
pop ah
jmp swtend ; Equivalent to "break"
b:
push ah
mov al, 'b'
mov ah, 0Eh
mov bh, 00h
int 10h
pop ah
jmp swtend ; Equivalent to "break"
...
swtend:

Alternatives

Some alternatives to using a switch statement include:
; if-then-else: A series of if-then-else conditionals can test for each case value; one at a time. Fall through can be achieved with a sequence of if conditionals each without the else clause.
; Control table: The logic of a switch statement can be encoded as a control table that is keyed by the case values and each value encodes what is otherwise in the case section as a function pointer or anonymous function or similar mechanism.
; Pattern matching: Pattern matching is switch-like functionality used in many functional programming languages.