In
computer programming language
A programming language is a system of notation for writing computer program, computer programs. Most programming languages are text-based formal languages, but they may also be visual programming language, graphical. They are a kind of computer ...
s, a switch statement is a type of selection control mechanism used to allow the value of a
variable or expression to change the
control flow
In computer science, control flow (or flow of control) is the order in which individual statements, instructions or function calls of an imperative program are executed or evaluated. The emphasis on explicit control flow distinguishes an '' ...
of program execution via search and map.
Switch statements function somewhat similarly to the
if
statement used in programming languages like
C/
C++,
C#,
Visual Basic .NET,
Java
Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's mo ...
and exists in most high-level
imperative programming
In computer science, imperative programming is a programming paradigm of software that uses statements that change a program's state. In much the same way that the imperative mood in natural languages expresses commands, an imperative program co ...
languages such as
Pascal,
Ada,
C/
C++,
C#,
Visual Basic .NET,
Java
Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's mo ...
, and in many other types of language, using such
keywords as
switch
,
case
,
select
or
inspect
.
Switch statements come in two main variants: a structured switch, as in Pascal, which takes exactly one branch, and an unstructured switch, as in C, which functions as a type of
goto
GoTo (goto, GOTO, GO TO or other case combinations, depending on the programming language) is a statement found in many computer programming languages. It performs a one-way transfer of control to another line of code; in contrast a function c ...
. The main reasons for using a switch include improving clarity, by reducing otherwise repetitive coding, and (if the
heuristic
A heuristic (; ), or heuristic technique, is any approach to problem solving or self-discovery that employs a practical method that is not guaranteed to be optimal, perfect, or rational, but is nevertheless sufficient for reaching an immediat ...
s permit) also offering the potential for faster execution through easier
compiler optimization
In computing, an optimizing compiler is a compiler that tries to minimize or maximize some attributes of an executable computer program. Common requirements are to minimize a program's execution time, memory footprint, storage size, and power c ...
in many cases.
History
In his 1952 text ''Introduction to Metamathematics'',
Stephen Kleene formally proved that the CASE function (the IF-THEN-ELSE function being its simplest form) is a
primitive recursive function
In computability theory, a primitive recursive function is roughly speaking a function that can be computed by a computer program whose loops are all "for" loops (that is, an upper bound of the number of iterations of every loop can be determined ...
, where he defines the notion
definition by cases
in the following manner:
:"#F. The function φ defined thus
:: φ(x
1 , ... , x
n ) =
:::*φ
1(x
1 , ... , x
n ) if Q
1(x
1 , ... , x
n ),
:::* . . . . . . . . . . . .
:::*φ
m(x
1 , ... , x
n ) if Q
m(x
1 , ... , x
n ),
:::*φ
m+1(x
1 , ... , x
n ) otherwise,
:where Q
1 , ... , Q
m are mutually exclusive predicates (or φ(x
1 , ... , x
n) shall have the value given by the first clause which applies) is primitive recursive in φ
1, ..., φ
m+1, Q
1, ..., Q
m+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.
Boolos-Burgess-Jeffrey make the additional observation that "definition by cases" must be both
mutually exclusive
In logic and probability theory, two events (or propositions) are mutually exclusive or disjoint if they cannot both occur at the same time. A clear example is the set of outcomes of a single coin toss, which can result in either heads or tails ...
and
collectively exhaustive
In probability theory and logic, a set of events is jointly or collectively exhaustive if at least one of the events must occur. For example, when rolling a six-sided die, the events 1, 2, 3, 4, 5, and 6 balls of a single outcome are collecti ...
. They too offer a proof of the primitive recursiveness of this function (Boolos-Burgess-Jeffrey 2002:74-75).
The IF-THEN-ELSE is the basis of the
McCarthy formalism: its usage replaces both primitive recursion and the
mu-operator.
Typical syntax
In most languages, programmers write a switch statement across many individual lines using one or two keywords. A typical syntax involves:
* the first
select
, followed by an expression which is often referred to as the ''control expression'' or ''control variable'' of the switch statement
* subsequent lines defining the actual cases (the values), with corresponding sequences of statements for execution when a match occurs
* In languages with fallthrough behaviour, a
break
statement typically follows a
case
statement to end said statement.
ells Ells may refer to:
* Ell, a measure of length
* Ell (architecture)
* Ells (surname), a surname
* Ells Field, an airport in Mendocino County, California, United States
* Ells River, in Alberta, Canada
* Euroleague for Life Sciences
The Euroleague ...
* In some languages, e.g.,
PL/I
PL/I (Programming Language One, pronounced and sometimes written PL/1) is a procedural, imperative computer programming language developed and published by IBM. It is designed for scientific, engineering, business and system programming. It ...
, the control expression is optional; if there is no control expression then each alternative begins with a
WHEN
clause containing a boolean expression and a match occurs for the first case for which that expression evaluates to true. This usage is similar to the if/then/elseif/else structures in some other languages, e.g.,
Perl
Perl is a family of two High-level programming language, high-level, General-purpose programming language, general-purpose, Interpreter (computing), interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it ...
.
* In some languages, e.g.,
Rexx
Rexx (Restructured Extended Executor) is a programming language that can be interpreted or compiled. It was developed at IBM by Mike Cowlishaw. It is a structured, high-level programming language designed for ease of learning and reading. ...
, no control expression is allowed and each alternative begins with a
WHEN
clause containing a boolean expression and a match occurs for the first case for which that expression evaluates to true.
Each alternative begins with the particular value, or list of values (see below), that the control variable may match and which will cause the control to
goto
GoTo (goto, GOTO, GO TO or other case combinations, depending on the programming language) is a statement found in many computer programming languages. It performs a one-way transfer of control to another line of code; in contrast a function c ...
the corresponding sequence of statements. The value (or list/range of values) is usually separated from the corresponding statement sequence by a colon or by an implication arrow. In many languages, every case must also be preceded by a keyword such as
case
or
when
.
An optional default case is typically also allowed, specified by a
default
,
otherwise
, or
else
keyword. This executes when none of the other cases match the control expression. In some languages, such as C, if no case matches and the
default
is omitted the
switch
statement simply exits. In others, like PL/I, an error is raised.
Semantics
Semantically, there are two main forms of switch statements.
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 functions as a generalized if–then–else
conditional
Conditional (if then) may refer to:
* Causal conditional, if X then Y, where X is a cause of Y
* Conditional probability, the probability of an event A given that another event B has occurred
*Conditional proof, in logic: a proof that asserts a ...
, here with any number of branches, not just two.
The second form are unstructured switches, as in C, where the cases are treated as labels within a single block, and the switch functions as a generalized goto. This distinction is referred to as the treatment of fallthrough, which is elaborated below.
Fallthrough
In many languages, only the matching block is executed, and then execution continues at the end of the switch statement. These include the
Pascal family (Object Pascal, Modula, Oberon, Ada, etc.) as well as
PL/I
PL/I (Programming Language One, pronounced and sometimes written PL/1) is a procedural, imperative computer programming language developed and published by IBM. It is designed for scientific, engineering, business and system programming. It ...
, modern forms of
Fortran and
BASIC
BASIC (Beginners' All-purpose Symbolic Instruction Code) is a family of general-purpose, high-level programming languages designed for ease of use. The original version was created by John G. Kemeny and Thomas E. Kurtz at Dartmouth College ...
dialects influenced by Pascal, most functional languages, and many others. To allow multiple values to execute the same code (and avoid needing to
duplicate code In computer programming, duplicate code is a sequence of source code that occurs more than once, either within a program or across different programs owned or maintained by the same entity. Duplicate code is generally considered undesirable for a nu ...
), Pascal-type languages permit any number of values per case, given as a comma-separated list, as a range, or as a combination.
Languages derived from C language, and more generally those influenced by Fortran's
computed GOTO
GoTo (goto, GOTO, GO TO or other case combinations, depending on the programming language) is a statement found in many computer programming languages. It performs a one-way transfer of control to another line of code; in contrast a function c ...
, instead feature fallthrough, where control moves to the matching case, and then execution continues ("falls through") to the statements associated with the ''next'' case in the source text. This also allows multiple values to match the same point without any special syntax: they are just listed with empty bodies. Values can be
special condition
Special or specials may refer to:
Policing
* Specials, Ulster Special Constabulary, the Northern Ireland police force
* Specials, Special Constable, an auxiliary, volunteer, or temporary; police worker or police officer
Literature
* ''Specia ...
ed with code in the case body. In practice, fallthrough is usually prevented with a
break
keyword at the end of the matching body, which exits execution of the switch block, but this can cause bugs due to unintentional fallthrough if the programmer forgets to insert the
break
statement. This is thus seen by many as a language wart, and warned against in some lint tools. Syntactically, the cases are interpreted as labels, not blocks, and the switch and break statements explicitly change control flow. Some languages influenced by C, such as
JavaScript
JavaScript (), often abbreviated as JS, is a programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. As of 2022, 98% of Website, websites use JavaScript on the Client (computing), client side ...
, retain default fallthrough, while others remove fallthrough, or only allow it in special circumstances. Notable variations on this in the C-family include
C#, in which all blocks must be terminated with a
break
or
return
unless the block is empty (i.e. fallthrough is used as a way to specify multiple values).
In some cases languages provide optional fallthrough. For example,
Perl
Perl is a family of two High-level programming language, high-level, General-purpose programming language, general-purpose, Interpreter (computing), interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it ...
does not fall through by default, but a case may explicitly do so using a
continue
keyword. This prevents unintentional fallthrough but allows it when desired. Similarly,
Bash defaults to not falling through when terminated with
;;
, but allow fallthrough with
;&
or
;;&
instead.
An example of a switch statement that relies on fallthrough is
Duff's device.
Compilation
Optimizing compilers such as
GCC or
Clang
Clang is a compiler front end for the C, C++, Objective-C, and Objective-C++ programming languages, as well as the OpenMP, OpenCL, RenderScript, CUDA, and HIP frameworks. It acts as a drop-in replacement for the GNU Compiler Collection ...
may compile a switch statement into either a
branch table
In computer programming, a branch table or jump table is a method of transferring program control ( branching) to another part of a program (or a different program that may have been dynamically loaded) using a table of branch or jump instruction ...
or a
binary search
In computer science, binary search, also known as half-interval search, logarithmic search, or binary chop, is a search algorithm that finds the position of a target value within a sorted array. Binary search compares the target value to the m ...
through the values in the cases.
A branch table allows the switch statement to determine with a small, constant number of instructions which branch to execute without having to go through a list of comparisons, while a binary search takes only a logarithmic number of comparisons, measured in the number of cases in the switch statement.
Normally, the only method of finding out if this optimization has occurred is by actually looking at the resultant
assembly
Assembly may refer to:
Organisations and meetings
* Deliberative assembly, a gathering of members who use parliamentary procedure for making decisions
* General assembly, an official meeting of the members of an organization or of their representa ...
or
machine code
In computer programming, machine code is any low-level programming language, consisting of machine language instructions, which are used to control a computer's central processing unit (CPU). Each instruction causes the CPU to perform a ver ...
output that has been generated by the compiler.
Advantages and disadvantages
In some languages and programming environments, the use of a
case
or
switch
statement is considered superior to an equivalent series of ''if
else if'' statements because it is:
* Easier to debug (e.g. setting breakpoints on code vs. a call table, if the debugger has no conditional breakpoint capability)
* Easier for a person to read
* Easier to understand, and consequently easier to maintain
* Fixed depth: a sequence of "if else if" statements may yield deep nesting, making compilation more difficult (especially in automatically generated code)
* Easier to verify that all values are handled. Compilers can issue a warning if some enum values are not handled.
Additionally, an
optimized implementation may execute much faster than the alternative, because it is often implemented by using an indexed
branch table
In computer programming, a branch table or jump table is a method of transferring program control ( branching) to another part of a program (or a different program that may have been dynamically loaded) using a table of branch or jump instruction ...
. 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 length
In computer performance, the instruction path length is the number of machine code instructions required to execute a section of a computer program. The total path length for the entire program could be deemed a measure of the algorithm's performa ...
s considerably. When implemented as such, a switch statement essentially becomes a
perfect hash.
In terms of the
control-flow graph
In computer science, a control-flow graph (CFG) is a representation, using graph notation, of all paths that might be traversed through a program during its execution. The control-flow graph was discovered by Frances E. Allen, who noted tha ...
, a switch statement consists of two nodes (entrance and exit), plus one edge between them for each option. By contrast, a sequence of "if...else if...else if" 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, with these not adding any useful information. However, the simple branches in the if statements are individually conceptually easier than the complex branch of a switch statement. In terms of
cyclomatic complexity
Cyclomatic complexity is a software metric used to indicate the complexity of a program. It is a quantitative measure of the number of linearly independent paths through a program's source code. It was developed by Thomas J. McCabe, Sr. in 1976. ...
, both of these options increase it by ''k''−1 if given ''k'' cases.
Switch expressions
''Switch expressions'' are introduced in
Java SE 12, 19 March 2019, as a preview feature. Here a whole switch expression can be used to return a value. There is also a new form of case label, where the right-hand-side is a single expression. This also prevents fall though and requires that cases are exhaustive. In Java SE 13 the
yield
statement is introduced, and in Java SE 14 switch expressions becomes a standard language feature. For example:
int ndays = switch(month) ;
Alternative uses
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.
PHP
For example, in
PHP
PHP is a General-purpose programming language, general-purpose scripting language geared toward web development. It was originally created by Danish-Canadian programmer Rasmus Lerdorf in 1993 and released in 1995. The PHP reference implementati ...
, a constant can be used as the "variable" to check against, and the first case statement which evaluates to that constant will be executed:
switch (true)
switch (5)
This feature is also useful for checking multiple variables against one value rather than one variable against many values. COBOL also supports this form (and others forms) in the
EVALUATE
statement. 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.
Ruby
In
Ruby
A ruby is a pinkish red to blood-red colored gemstone, a variety of the mineral corundum (aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sapp ...
, due to its handling of
equality, the statement can be used to test for variable’s class:
case input
when Array then puts 'input is an Array!'
when Hash then puts 'input is a Hash!'
end
Ruby also returns a value that can be assigned to a variable, and doesn’t actually require the
case
to have any parameters (acting a bit like an
else if
statement):
catfood =
case
when cat.age <= 1
junior
when cat.age > 10
senior
else
normal
end
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:
Python
For Python 3.10.6,
PEPs 634-636 were accepted, which added and keywords.
Unlike other languages, Python notably doesn't exhibit fallthrough behavior.
letter = input("Put in a single letter: ").strip() casefold() # first non-whitespace character of the input, lowercase
match letter:
case 'a' , 'e' , 'i' , 'o' , 'u': # Unlike conditions in if statements, the `or` keyword cannot be used here to differentiate between cases
print(f"Letter is a vowel!")
case 'y':
print(f"Letter may be a vowel, just not in English.")
case _: # `case _` is equivalent to `default` from C and others
print(f"Letter is not a vowel!")
Exception handling
A number of languages implement a form of switch statement in
exception handling
In computing and computer programming, exception handling is the process of responding to the occurrence of ''exceptions'' – anomalous or exceptional conditions requiring special processing – during the execution of a program. In general, a ...
, 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
Modula-3 is a programming language conceived as a successor to an upgraded version of Modula-2 known as Modula-2+. While it has been influential in research circles (influencing the designs of languages such as Java, C#, and Python) it has not ...
, which use the
TRY
...
EXCEPT
syntax, where each
EXCEPT
defines a case. This is also found in
Delphi
Delphi (; ), in legend previously called Pytho (Πυθώ), in ancient times was a sacred precinct that served as the seat of Pythia, the major oracle who was consulted about important decisions throughout the ancient classical world. The oracl ...
,
Scala, and
Visual Basic .NET.
Alternatives
Some alternatives to switch statements can be:
* A series of ''if-else''
conditionals that examine the target one value at a time. Fallthrough behavior can be achieved with a sequence of ''if'' conditionals each without the ''else'' clause.
* A
lookup table
In computer science, a lookup table (LUT) is an array that replaces runtime computation with a simpler array indexing operation. The process is termed as "direct addressing" and LUTs differ from hash tables in a way that, to retrieve a value v w ...
, which contains, as keys, the
case
values and, as values, the part under the
case
statement.
::(In some languages, only actual data types are allowed as values in the lookup table. In other languages, it is also possible to assign
functions as lookup table values, gaining the same flexibility as a real
switch
statement. See
Control table
Control tables are tables that control the control flow or play a major part in program control. There are no rigid rules about the structure or content of a control table—its qualifying attribute is its ability to direct control flow in some wa ...
article for more detail on this).
::
Lua
Lua or LUA may refer to:
Science and technology
* Lua (programming language)
* Latvia University of Agriculture
* Last universal ancestor, in evolution
Ethnicity and language
* Lua people, of Laos
* Lawa people, of Thailand sometimes referred t ...
does not support case/switch statements.
This lookup technique is one way to implement
switch
statements in the Lua language, which has no built-in
switch
.
[Switch statement in Lua](_blank)
/ref>
::In some cases, lookup tables are more efficient than non- optimized switch
statements since many languages can optimize table lookups, whereas switch statements are not optimized unless the range of values is small with few gaps. A non-optimized, non-binary search
In computer science, binary search, also known as half-interval search, logarithmic search, or binary chop, is a search algorithm that finds the position of a target value within a sorted array. Binary search compares the target value to the m ...
lookup, however, will almost certainly be slower than either a non-optimized switch or the equivalent multiple ''if-else'' statements.
* A control table
Control tables are tables that control the control flow or play a major part in program control. There are no rigid rules about the structure or content of a control table—its qualifying attribute is its ability to direct control flow in some wa ...
(that may be implemented as a simple lookup table) can also be customized to accommodate multiple conditions on multiple inputs if required and usually exhibits greater 'visual compactness' than an equivalent switch (that can occupy many statements).
* Pattern matching
In computer science, pattern matching is the act of checking a given sequence of tokens for the presence of the constituents of some pattern. In contrast to pattern recognition, the match usually has to be exact: "either it will or will not be ...
, which is used to implement switch-like functionality in many functional
Functional may refer to:
* Movements in architecture:
** Functionalism (architecture)
** Form follows function
* Functional group, combination of atoms within molecules
* Medical conditions without currently visible organic basis:
** Functional s ...
languages.
See also
* Algorithmic efficiency
In computer science, algorithmic efficiency is a property of an algorithm which relates to the amount of computational resources used by the algorithm. An algorithm must be analyzed to determine its resource usage, and the efficiency of an al ...
* Branch table
In computer programming, a branch table or jump table is a method of transferring program control ( branching) to another part of a program (or a different program that may have been dynamically loaded) using a table of branch or jump instruction ...
* Control table
Control tables are tables that control the control flow or play a major part in program control. There are no rigid rules about the structure or content of a control table—its qualifying attribute is its ability to direct control flow in some wa ...
* Duff's device
* Index mapping
Index mapping (or direct addressing, or a trivial hash function) in computer science describes using an array, in which each position corresponds to a key in the universe of possible values.
The technique is most effective when the universe of keys ...
References
Further reading
* Stephen Kleene, 1952 (10th reprint 1991), ''Introduction to Metamathematics'', North-Holland Publishing Company, Amsterdam NL,
* George Boolos
George Stephen Boolos (; 4 September 1940 – 27 May 1996) was an American philosopher and a mathematical logician who taught at the Massachusetts Institute of Technology.
Life
Boolos is of Greek-Jewish descent. He graduated with an A.B. ...
, John Burgess, and Richard Jeffrey
Richard Carl Jeffrey (August 5, 1926 – November 9, 2002) was an American philosopher, logician, and probability theorist. He is best known for developing and championing the philosophy of radical probabilism and the associated heuristic of ...
, 2002, ''Computability and Logic: Fourth Edition'', Cambridge University Press, Cambridge UK, {{ISBN, 0-521-00758-5 paperback. cf page 74-75.
Conditional constructs
ru:Оператор ветвления#Переключатель (оператор множественного выбора)