The main reasons for using a switch include improving clarity, by reducing otherwise repetitive coding, and (if the heuristics permit) also offering the potential for faster execution through easier compiler optimization in many cases.
where Q1 , ... , Qm are mutually exclusive predicates (or φ(x1 , ... , xn) shall have the value given by the first clause which applies) is primitive recursive in φ1, ..., φm+1, Q1, ..., Qm+1.Kleene provides a proof of this in terms of the Boolean-like recursive functions "sign-of" sg( ) and "not sign of" ~sg( ) (Kleene 1952:222-223); the first returns 1 if its input is positive and −1 if its input is negative.
Early ALGOL compilers supported a SWITCH data type which contains a list of "designational expressions".
A GOTO statement could reference a switch variable and, by providing an index, branch to the desired destination.
With experience it was realized that a more formal multi-way construct, with single point of entrance and exit, was needed.
The first form are structured switches, as in Pascal, where exactly one branch is taken, and the cases are treated as separate, exclusive blocks.
This also allows multiple values to match the same point without any special syntax: they are just listed with empty bodies.
Syntactically, the cases are interpreted as labels, not blocks, and the switch and break statements explicitly change control flow.
Normally, the only method of finding out if this optimization has occurred is by actually looking at the resultant assembly or machine code output that has been generated by the compiler.
[7] For example, deciding program flow based on a single character's value, if correctly implemented, is vastly more efficient than the alternative, reducing instruction path lengths considerably.
In terms of the control-flow graph, a switch statement consists of two nodes (entrance and exit), plus one edge between them for each option.
[8][9][10] For example: Many languages evaluate expressions inside switch blocks at runtime, allowing a number of less obvious uses for the construction.
This prohibits certain compiler optimizations, so is more common in dynamic and scripting languages where the enhanced flexibility is more important than the performance overhead.
PL/I has an alternative form of the SELECT statement where the control expression is omitted altogether and the first WHEN that evaluates to true is executed.