Switch statement
Encyclopedia
In computer programming
, a switch, case, select or inspect statement
is a type of selection control mechanism that exists in most imperative programming
languages such as Pascal
, Ada
, C
/C++
, C#, Java
, and so on. It is also included in several other types of languages. Its purpose is to allow the value of a variable
or expression to control the flow of program execution via a multiway branch
(or "goto
", one of several label
s). The main reasons for using a switch include improving clarity, by reducing otherwise repetitive coding, and (if the heuristic
s permit) also offering the potential for faster execution through easier compiler optimization
in many cases.
, where he defines the notion definition by cases in the following manner:
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 and collectively exhaustive. 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.
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 go to the corresponding sequence of statements. The value (or list/range of values) is usually separated from the corresponding statement sequence by a colon or 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 or else keyword; this is executed when none of the other cases matches the control expression.
In languages derived from C, a break keyword is used to go to the end of the switch, thus completing execution of the switch statement. In such languages, program execution "falls through" to the statements associated with the next case in the source text when no break is present, thereby behaving like a GOTO mechanism. Notable variations on this in the C-family include C#, in which all blocks must be terminated with a break unless the block is empty (i.e. fallthrough is used as a way to specify multiple values).
The Pascal
family (Object Pascal, Modula, Oberon, Ada, etc.) as well as modern BASIC
dialects influenced by Pascal, do not allow fallthrough. The same goes for most functional languages and many others. Pascal type languages instead permit any number of values per case, given as a comma separated list, as a range, or a combination. Perl
is a language where cases do not fall through by default, but may explicitly do so using a continue keyword.
may actually implement the switch statement as a branch table
or an array of indexed function pointer
s instead of a lengthy series of conditional instructions. This allows the switch statement to determine instantly what branch to execute without having to go through a list of comparisons.
See algorithmic efficiency
for an explanation of how the programmer can "assist" the compiler to make an efficient choice.
See also the section 'Compiler generated branch tables' in branch table
article for why optimization is not always performed as expected and how to solve this.
or machine code
output that has been generated by the compiler (and is therefore seldom, if ever, done by HLL
programmers).
The first 'C' example below would be eligible for this kind of optimization if the compiler supported it (the range '0' through '9' with zero gaps without a defined case label).
Additionally, as mentioned above, an optimized
implementation may:
does not allow “fall through”; it uses case, when and others. Ada requires full coverage of all possible values for the type in the case statement. If a when others =>
case is not specified, then the code will not compile if either extra cases are specified, or missing.
If at some point in the future, the definition of Digit is modified, the compiler will ensure that the programmer updates the case statement to reflect the changes to the type definition, which ensures that the program is kept up to date and helps to reduce maintenance costs.
A list of values for a particular case can be combined using '|' as shown below, or a range of values
may be specified using ".." to indicate the extents of the range. e.g., when 0 .. 4 => Put_Line ("Small Digits);
In the example below, there is no need to check for values outside the range of 0 to 9 because the type is guaranteed to have a value within the range for the type.
a switch is effectively an array of labels (branch table
). A switch declaration defines its values (i.e., for each index value the name of a label occurring somewhere in the program). A goto statement can specify as destination, instead of a fixed label, an "array element" of this switch, i.e., the switch identifier with, in brackets, the index.
and similarly-constructed languages, the lack of break keywords to cause fall through of program execution from one block to the next is used extensively. For example, if n=2, the fifth case statement will produce a match to the control variable. The next line outputs "n is an even number.". Execution then continues through the next 3 case statements and to the next line, which outputs "n is a prime number." this is a classic example of omitting the break line to allow for fall through. The break line after a case block causes the switch statement to conclude. If the user types in more than one digit, the default block is executed, producing an error message by executing the default code.
C# also allows the use of non-integer case values, such as Strings.
's multi-branch instruction uses inspect, when, and else. It does not have the “fall through” behavior. Also, the else part is optional. However, an omitted else differs from an included, but empty else. If the else is empty and a case is processed that is not specified in one of the when parts, control passes through the else. But if the else is omitted, it is assumed that all cases should be identified in a when part. In this case an exception will occur as a result of processing a case not handled in a when part.
has an explicit fallthrough statement which can be used at the end of a case statement to indicate that control falls through next case clause in a expression "switch" statement.
which returns a value, and it can deconstruct values using pattern matching
.
does not allow “fall through”, but has ranges and comma separated literal lists.
5.10 (backported from Perl 6
) has a powerful built in switch statement called given, where the cases are called when:
does not have direct language support for the switch statement; 'if'/'elif' is often used for that. However, it is possible to emulate this behaviour, through a dictionary
of functions.
Here is an example that does not use a “fall through” mechanism. The default case is mimicked by using dict.get's fallback parameter:
doesn’t allow “fall through”; it uses case, when and else:
Also can be used to assign a value, in a more compact way:
This can be shortened to an equivalent
, the switch statement is called "Select Case", and fall-through to later blocks is not supported.
However, ranges and various constructs from If statements are both supported
:
, the switch statement is called "Select Case", and fall-through to later blocks is not supported. Short-circuit evaluation is used. But also, may doing exactly like C, using GOSUB
behind Select Case. the block Select Case then call to GOSUB label, where each BREAK in C it's a RETURN (to gosub).
example is easy to understand:
employs a construct whereby the action to be taken is enclosed in a scriptblock (i.e. curly braces), with the selector placed directly before it. The selector can consist of regular expressions if the "-regex" parameter is inserted after the "switch" command; similarly, wildcards are supported using the "-wildcard" parameter. In either case, the wildcard or regex must be enclosed in quote marks.
Akin to C-based implementations, if a "break" statement is not included at the end of a scriptblock, the switch statement will continue to test each case and execute further scriptblocks.
s and has no influence on the performance or behavior of the program. This style of switch statement is commonly used for finite state machine
implementation. Here are some examples, given in Pascal (one of the first languages implementing enumerations, along with Algol68) as well as in C (which has a tradition of constants in all capitals, although not enforced by the compiler.)
For example, in PHP
, a constant can be used as the "variable" to check against, and the first case statement which evaluates to that constant will be executed:
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.
In Ruby
, due to its handling of
Ruby also returns a value that can be assigned to a variable, and doesn’t actually require the
Computer programming
Computer programming is the process of designing, writing, testing, debugging, and maintaining the source code of computer programs. This source code is written in one or more programming languages. The purpose of programming is to create a program that performs specific operations or exhibits a...
, a switch, case, select or inspect statement
Statement (programming)
In computer programming a statement can be thought of as the smallest standalone element of an imperative programming language. A program written in such a language is formed by a sequence of one or more statements. A statement will have internal components .Many languages In computer programming...
is a type of selection control mechanism that exists in most imperative programming
Imperative programming
In computer science, imperative programming is a programming paradigm that describes computation in terms of statements that change a program state...
languages such as Pascal
Pascal (programming language)
Pascal is an influential imperative and procedural programming language, designed in 1968/9 and published in 1970 by Niklaus Wirth as a small and efficient language intended to encourage good programming practices using structured programming and data structuring.A derivative known as Object Pascal...
, Ada
Ada (programming language)
Ada is a structured, statically typed, imperative, wide-spectrum, and object-oriented high-level computer programming language, extended from Pascal and other languages...
, C
C (programming language)
C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system....
/C++
C++
C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. It is regarded as an intermediate-level language, as it comprises a combination of both high-level and low-level language features. It was developed by Bjarne Stroustrup starting in 1979 at Bell...
, C#, Java
Java (programming language)
Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities...
, and so on. It is also included in several other types of languages. Its purpose is to allow the value of a variable
Variable (programming)
In computer programming, a variable is a symbolic name given to some known or unknown quantity or information, for the purpose of allowing the name to be used independently of the information it represents...
or expression to control the flow of program execution via a multiway branch
Multiway branch
Multiway branch is a computer science term used to describe the change to a program's control flow based upon a value matching a selected criteria. It is a form of conditional statement...
(or "goto
Goto
goto is a statement found in many computer programming languages. It is a combination of the English words go and to. It performs a one-way transfer of control to another line of code; in contrast a function call normally returns control...
", one of several label
Label (programming language)
A label in a programming language is a sequence of characters that identifies a location within source code. In most languages labels take the form of an identifier, often followed by a punctuation character . In many high level programming languages the purpose of a label is to act as the...
s). The main reasons for using a switch include improving clarity, by reducing otherwise repetitive coding, and (if the heuristic
Heuristic
Heuristic refers to experience-based techniques for problem solving, learning, and discovery. Heuristic methods are used to speed up the process of finding a satisfactory solution, where an exhaustive search is impractical...
s permit) also offering the potential for faster execution through easier compiler optimization
Compiler optimization
Compiler optimization is the process of tuning the output of a compiler to minimize or maximize some attributes of an executable computer program. The most common requirement is to minimize the time taken to execute a program; a less common one is to minimize the amount of memory occupied...
in many cases.
History
In his 1952 text Introduction to Metamathematics, Stephen Kleene formally proves that the CASE function (the IF-THEN-ELSE function being its simplest form) is a primitive recursive functionPrimitive recursive function
The primitive recursive functions are defined using primitive recursion and composition as central operations and are a strict subset of the total µ-recursive functions...
, where he defines the notion definition by cases in the following manner:
- "#F. The function φ defined thus
- φ(x1 , ... , xn ) =
-
- φ1(x1 , ... , xn ) if Q1(x1 , ... , xn ),
- . . . . . . . . . . . .
- φm(x1 , ... , xn ) if Qm(x1 , ... , xn ),
- φm+1(x1 , ... , xn ) otherwise,
-
- φ(x1 , ... , xn ) =
- 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. (Definition by cases)." (Kleene 1952:229)
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 and collectively exhaustive. 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
McCarthy Formalism
In computer science and recursion theory the McCarthy Formalism of computer scientist John McCarthy clarifies the notion of recursive functions by use of the IF-THEN-ELSE construction common to computer science, together with the four of the operators of primitive recursive functions: zero,...
– its usage replaces both primitive recursion and the mu-operator.
Typical syntax
In most languages, a switch statement is defined across many individual lines using one or two keywords. A typical syntax is:- The first line contains the basic keyword, usually switch, case or select, followed by an expression which is often referred to as the control expression or control variable of the switch statement.
- Subsequent lines define the actual cases (the values) with corresponding sequences of statements that should be executed when a match occur.
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 go to the corresponding sequence of statements. The value (or list/range of values) is usually separated from the corresponding statement sequence by a colon or 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 or else keyword; this is executed when none of the other cases matches the control expression.
In languages derived from C, a break keyword is used to go to the end of the switch, thus completing execution of the switch statement. In such languages, program execution "falls through" to the statements associated with the next case in the source text when no break is present, thereby behaving like a GOTO mechanism. Notable variations on this in the C-family include C#, in which all blocks must be terminated with a break unless the block is empty (i.e. fallthrough is used as a way to specify multiple values).
The Pascal
Pascal
Pascal or PASCAL may refer to:-People:* Pascal , a French given name* Pascal , a French and Italian surname* Adam Pascal , American actor and singer, best known for his role of Roger Davis in the Broadway musical Rent* Blaise Pascal , French mathematician and philosopher* Cleo Paskal, environmental...
family (Object Pascal, Modula, Oberon, Ada, etc.) as well as modern BASIC
BASIC
BASIC is a family of general-purpose, high-level programming languages whose design philosophy emphasizes ease of use - the name is an acronym from Beginner's All-purpose Symbolic Instruction Code....
dialects influenced by Pascal, do not allow fallthrough. The same goes for most functional languages and many others. Pascal type languages instead permit any number of values per case, given as a comma separated list, as a range, or a combination. Perl
Perl
Perl is a high-level, general-purpose, interpreted, dynamic programming language. Perl was originally developed by Larry Wall in 1987 as a general-purpose Unix scripting language to make report processing easier. Since then, it has undergone many changes and revisions and become widely popular...
is a language where cases do not fall through by default, but may explicitly do so using a continue keyword.
Compilation
If the range of input values is identifiably 'small' and has only a few gaps, some compilers that incorporate an optimizerOptimization (computer science)
In computer science, program optimization or software optimization is the process of modifying a software system to make some aspect of it work more efficiently or use fewer resources...
may actually implement the switch statement as a branch table
Branch table
In computer programming, a branch table is a term used to describe an efficient method of transferring program control to another part of a program using a table of branch instructions. It is a form of multiway branch...
or an array of indexed function pointer
Function pointer
A function pointer is a type of pointer in C, C++, D, and other C-like programming languages, and Fortran 2003. When dereferenced, a function pointer can be used to invoke a function and pass it arguments just like a normal function...
s instead of a lengthy series of conditional instructions. This allows the switch statement to determine instantly what branch to execute without having to go through a list of comparisons.
Optimized switch
To optimize a switch statement, the programmer must use a very compact range of possible values to test. Sometimes it is necessary to convert the switch to a more suitable range using an inexpensive transformation.See algorithmic efficiency
Algorithmic efficiency
In computer science, efficiency is used to describe properties of an algorithm relating to how much of various types of resources it consumes. Algorithmic efficiency can be thought of as analogous to engineering productivity for a repeating or continuous process, where the goal is to reduce...
for an explanation of how the programmer can "assist" the compiler to make an efficient choice.
See also the section 'Compiler generated branch tables' in branch table
Branch table
In computer programming, a branch table is a term used to describe an efficient method of transferring program control to another part of a program using a table of branch instructions. It is a form of multiway branch...
article for why optimization is not always performed as expected and how to solve this.
Checking for optimization
Normally, the only method of finding out if this optimization has occurred is by actually looking at the resultant assemblyAssembly language
An assembly language is a low-level programming language for computers, microprocessors, microcontrollers, and other programmable devices. It implements a symbolic representation of the machine codes and other constants needed to program a given CPU architecture...
or machine code
Machine code
Machine code or machine language is a system of impartible instructions executed directly by a computer's central processing unit. Each instruction performs a very specific task, typically either an operation on a unit of data Machine code or machine language is a system of impartible instructions...
output that has been generated by the compiler (and is therefore seldom, if ever, done by HLL
High-level programming language
A high-level programming language is a programming language with strong abstraction from the details of the computer. In comparison to low-level programming languages, it may use natural language elements, be easier to use, or be from the specification of the program, making the process of...
programmers).
The first 'C' example below would be eligible for this kind of optimization if the compiler supported it (the range '0' through '9' with zero gaps without a defined case label).
Advantages
In some languages and programming environments, the use of a case or switch statement is considered superior to an equivalent series of if-else 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 to read (subjective)
- easier to understand and therefore
- easier to maintain
Additionally, as mentioned above, an optimized
Optimization (computer science)
In computer science, program optimization or software optimization is the process of modifying a software system to make some aspect of it work more efficiently or use fewer resources...
implementation may:
- execute much faster than the alternative, because it is often implemented by using an indexed branch tableBranch tableIn computer programming, a branch table is a term used to describe an efficient method of transferring program control to another part of a program using a table of branch instructions. It is a form of multiway branch...
- 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 lengthInstruction path lengthIn 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 performance on a particular computer hardware...
s considerably.
Disadvantages
When implemented with fall-through as the default path, switch/case statements are a frequent source of bugs among even experienced programmers, given that, in practice, the "break" is almost always the desired path, but not the default behavior of the switch/case construct (at least in C and Java).Examples
The following are simple examples, written in the various languages, that use switch (or switch-like) statements to print one of several possible lines, depending on the value of an integer entered by the user.Ada
AdaAda (programming language)
Ada is a structured, statically typed, imperative, wide-spectrum, and object-oriented high-level computer programming language, extended from Pascal and other languages...
does not allow “fall through”; it uses case, when and others. Ada requires full coverage of all possible values for the type in the case statement. If a when others =>
case is not specified, then the code will not compile if either extra cases are specified, or missing.
If at some point in the future, the definition of Digit is modified, the compiler will ensure that the programmer updates the case statement to reflect the changes to the type definition, which ensures that the program is kept up to date and helps to reduce maintenance costs.
A list of values for a particular case can be combined using '|' as shown below, or a range of values
may be specified using ".." to indicate the extents of the range. e.g., when 0 .. 4 => Put_Line ("Small Digits);
In the example below, there is no need to check for values outside the range of 0 to 9 because the type is guaranteed to have a value within the range for the type.
Algol 60
In Algol 60ALGOL 60
ALGOL 60 is a member of the ALGOL family of computer programming languages. It gave rise to many other programming languages, including BCPL, B, Pascal, Simula, C, and many others. ALGOL 58 introduced code blocks and the begin and end pairs for delimiting them...
a switch is effectively an array of labels (branch table
Branch table
In computer programming, a branch table is a term used to describe an efficient method of transferring program control to another part of a program using a table of branch instructions. It is a form of multiway branch...
). A switch declaration defines its values (i.e., for each index value the name of a label occurring somewhere in the program). A goto statement can specify as destination, instead of a fixed label, an "array element" of this switch, i.e., the switch identifier with, in brackets, the index.
C, C++, D, Java, PHP, ActionScript, JavaScript
In CC (programming language)
C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system....
and similarly-constructed languages, the lack of break keywords to cause fall through of program execution from one block to the next is used extensively. For example, if n=2, the fifth case statement will produce a match to the control variable. The next line outputs "n is an even number.". Execution then continues through the next 3 case statements and to the next line, which outputs "n is a prime number." this is a classic example of omitting the break line to allow for fall through. The break line after a case block causes the switch statement to conclude. If the user types in more than one digit, the default block is executed, producing an error message by executing the default code.
Clojure
Instead of switch/case syntax, clojure uses cond macroC#
In C#, every case block that contains any statements must have a reachable end point, or triggers a compilation error. Usually, this is a break statement, but any jump statement can be used – such as return, goto or throw – or the switch can simply end with an infinite loop. Case fall-through is only permitted when there are no statements between one case statement and the next. If fall-through is otherwise desired, it must be made explicit with the goto case construct.C# also allows the use of non-integer case values, such as Strings.
Eiffel
EiffelEiffel (programming language)
Eiffel is an ISO-standardized, object-oriented programming language designed by Bertrand Meyer and Eiffel Software. The design of the language is closely connected with the Eiffel programming method...
's multi-branch instruction uses inspect, when, and else. It does not have the “fall through” behavior. Also, the else part is optional. However, an omitted else differs from an included, but empty else. If the else is empty and a case is processed that is not specified in one of the when parts, control passes through the else. But if the else is omitted, it is assumed that all cases should be identified in a when part. In this case an exception will occur as a result of processing a case not handled in a when part.
Go
Like Perl, the Go programming languageGo (programming language)
Go is a compiled, garbage-collected, concurrent programming language developed by Google Inc.The initial design of Go was started in September 2007 by Robert Griesemer, Rob Pike, and Ken Thompson. Go was officially announced in November 2009. In May 2010, Rob Pike publicly stated that Go was being...
has an explicit fallthrough statement which can be used at the end of a case statement to indicate that control falls through next case clause in a expression "switch" statement.
Haskell
Haskell's case construct, unlike C-influenced languages, has no fall-through behaviour. It is an expressionExpression (programming)
An expression in a programming language is a combination of explicit values, constants, variables, operators, and functions that are interpreted according to the particular rules of precedence and of association for a particular programming language, which computes and then produces another value...
which returns a value, and it can deconstruct values using pattern matching
Pattern matching
In computer science, pattern matching is the act of checking some sequence of tokens for the presence of the constituents of some pattern. In contrast to pattern recognition, the match usually has to be exact. The patterns generally have the form of either sequences or tree structures...
.
OCaml, F#
OCaml and F#'s match construct is like Haskell's case above.Pascal
PascalPascal (programming language)
Pascal is an influential imperative and procedural programming language, designed in 1968/9 and published in 1970 by Niklaus Wirth as a small and efficient language intended to encourage good programming practices using structured programming and data structuring.A derivative known as Object Pascal...
does not allow “fall through”, but has ranges and comma separated literal lists.
Perl
PerlPerl
Perl is a high-level, general-purpose, interpreted, dynamic programming language. Perl was originally developed by Larry Wall in 1987 as a general-purpose Unix scripting language to make report processing easier. Since then, it has undergone many changes and revisions and become widely popular...
5.10 (backported from Perl 6
Perl 6
Perl 6 is a major revision to the Perl programming language. It is still in development, as a specification from which several interpreter and compiler implementations are being written. It is introducing elements of many modern and historical languages. Perl 6 is intended to have many...
) has a powerful built in switch statement called given, where the cases are called when:
Python
PythonPython (programming language)
Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. Python claims to "[combine] remarkable power with very clear syntax", and its standard library is large and comprehensive...
does not have direct language support for the switch statement; 'if'/'elif' is often used for that. However, it is possible to emulate this behaviour, through a dictionary
Associative array
In computer science, an associative array is an abstract data type composed of a collection of pairs, such that each possible key appears at most once in the collection....
of functions.
Here is an example that does not use a “fall through” mechanism. The default case is mimicked by using dict.get's fallback parameter:
QBasic
In QBasic, the switch statement is called "Select Case", and fall-through to later blocks is not supported. The "Select Case" statement is more expressive because it allows conditionals within cases.Ruby
RubyRuby (programming language)
Ruby is a dynamic, reflective, general-purpose object-oriented programming language that combines syntax inspired by Perl with Smalltalk-like features. Ruby originated in Japan during the mid-1990s and was first developed and designed by Yukihiro "Matz" Matsumoto...
doesn’t allow “fall through”; it uses case, when and else:
Also can be used to assign a value, in a more compact way:
Shell script
Bash and similar shell scripting languages offer a case construct using the OR operator,|
, to separate the selections, and the )
symbol to separate the list of selections from the action to be taken. Fall through is done using ;&
whereas ;;
acts as a case break.SQL
SQL has acase/when/then/else/end
expression:This can be shortened to an equivalent
decode
construct.Visual Basic .NET
In Visual Basic .NETVisual Basic .NET
Visual Basic .NET , is an object-oriented computer programming language that can be viewed as an evolution of the classic Visual Basic , which is implemented on the .NET Framework...
, the switch statement is called "Select Case", and fall-through to later blocks is not supported.
However, ranges and various constructs from If statements are both supported
Visual FoxPro
Visual FoxProVisual FoxPro
Visual FoxPro is a data-centric object-oriented and procedural programming language produced by Microsoft. It is derived from FoxPro which was developed by Fox Software beginning in 1984. Fox Technologies merged with Microsoft in 1992, after which the software acquired further features and the...
:
Visual Basic (classic), VBA, VB Script
In Visual BasicVisual Basic
Visual Basic is the third-generation event-driven programming language and integrated development environment from Microsoft for its COM programming model...
, the switch statement is called "Select Case", and fall-through to later blocks is not supported. Short-circuit evaluation is used. But also, may doing exactly like C, using GOSUB
GOSUB
GOSUB is a command in many versions of the BASIC computer programming language. A GOSUB statement jumps to a line elsewhere in the program. That line and the following lines up to a RETURN are used as a simple kind of a subroutine without parameters or local variables.The GOSUB command may be used...
behind Select Case. the block Select Case then call to GOSUB label, where each BREAK in C it's a RETURN (to gosub).
WebDNA
The WebDNAWebDNA
WebDNA is a server-side scripting, interpreted language containing an optional embedded, ram-resident, proprietary, searchable data structure. It has the ability to connect directly to other SQL servers if desired. Its primary use is in creating dynamic web page applications competing against the...
example is easy to understand:
Windows PowerShell
Windows PowerShellWindows PowerShell
Windows PowerShell is Microsoft's task automation framework, consisting of a command-line shell and associated scripting language built on top of, and integrated with the .NET Framework...
employs a construct whereby the action to be taken is enclosed in a scriptblock (i.e. curly braces), with the selector placed directly before it. The selector can consist of regular expressions if the "-regex" parameter is inserted after the "switch" command; similarly, wildcards are supported using the "-wildcard" parameter. In either case, the wildcard or regex must be enclosed in quote marks.
Akin to C-based implementations, if a "break" statement is not included at the end of a scriptblock, the switch statement will continue to test each case and execute further scriptblocks.
Symbolic constants
In many (but not all) circumstances, using symbolic names rather than explicit literal integers makes the source code easier to read and maintain. This is often achieved via enumerationEnumeration
In mathematics and theoretical computer science, the broadest and most abstract definition of an enumeration of a set is an exact listing of all of its elements . The restrictions imposed on the type of list used depend on the branch of mathematics and the context in which one is working...
s and has no influence on the performance or behavior of the program. This style of switch statement is commonly used for finite state machine
Finite state machine
A finite-state machine or finite-state automaton , or simply a state machine, is a mathematical model used to design computer programs and digital logic circuits. It is conceived as an abstract machine that can be in one of a finite number of states...
implementation. Here are some examples, given in Pascal (one of the first languages implementing enumerations, along with Algol68) as well as in C (which has a tradition of constants in all capitals, although not enforced by the compiler.)
Pascal (using an enumeration)
C (using the enum keyword)
Alternative uses
Many languages evaluate expressions insideswitch
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.For example, in PHP
PHP
PHP is a general-purpose server-side scripting language originally designed for web development to produce dynamic web pages. For this purpose, PHP code is embedded into the HTML source document and interpreted by a web server with a PHP processor module, which generates the web page document...
, a constant can be used as the "variable" to check against, and the first case statement which evaluates to that constant will be executed:
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.
In Ruby
Ruby (programming language)
Ruby is a dynamic, reflective, general-purpose object-oriented programming language that combines syntax inspired by Perl with Smalltalk-like features. Ruby originated in Japan during the mid-1990s and was first developed and designed by Yukihiro "Matz" Matsumoto...
, due to its handling of
equality, the statement can be used to test for variable’s class: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):Alternatives
- A series of nested if-else conditionals that examine the target one value at a time.
- A lookup tableLookup tableIn computer science, a lookup table is a data structure, usually an array or associative array, often used to replace a runtime computation with a simpler array indexing operation. The savings in terms of processing time can be significant, since retrieving a value from memory is often faster than...
, 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 tableControl tableControl tables are tables that control the program flow or play a major part in program control. There are no rigid rules concerning the structure or content of a control table - its only qualifying attribute is its ability to direct program flow in some way through its 'execution' by an associated...
article for more detail on this). - Lua does now support Case/Switch statements: http://lua-users.org/wiki/SwitchStatement . This lookup technique is one way to implement switch statements in the Lua language - which has no built-in switch.
- 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 lookup, however, will almost certainly be slower than either a non-optimized switch or the equivalent multiple if-else statements.
- A control tableControl tableControl tables are tables that control the program flow or play a major part in program control. There are no rigid rules concerning the structure or content of a control table - its only qualifying attribute is its ability to direct program flow in some way through its 'execution' by an associated...
(that may be implented 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). - For object-oriented programsObject-oriented programmingObject-oriented programming is a programming paradigm using "objects" – data structures consisting of data fields and methods together with their interactions – to design applications and computer programs. Programming techniques may include features such as data abstraction,...
, extensive use of polymorphismType polymorphismIn computer science, polymorphism is a programming language feature that allows values of different data types to be handled using a uniform interface. The concept of parametric polymorphism applies to both data types and functions...
can be used
- A control table
- (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
See also
- Algorithmic efficiencyAlgorithmic efficiencyIn computer science, efficiency is used to describe properties of an algorithm relating to how much of various types of resources it consumes. Algorithmic efficiency can be thought of as analogous to engineering productivity for a repeating or continuous process, where the goal is to reduce...
- general discussion on improving speed of algorithmAlgorithmIn mathematics and computer science, an algorithm is an effective method expressed as a finite list of well-defined instructions for calculating a function. Algorithms are used for calculation, data processing, and automated reasoning...
s - Branch tableBranch tableIn computer programming, a branch table is a term used to describe an efficient method of transferring program control to another part of a program using a table of branch instructions. It is a form of multiway branch...
- an extremely fast, optimized form of a switch statement used mostly in Assembler languages and compilerCompilerA compiler is a computer program that transforms source code written in a programming language into another computer language...
s - Control tableControl tableControl tables are tables that control the program flow or play a major part in program control. There are no rigid rules concerning the structure or content of a control table - its only qualifying attribute is its ability to direct program flow in some way through its 'execution' by an associated...
- a customizable switch-like array data structureData structureIn computer science, a data structure is a particular way of storing and organizing data in a computer so that it can be used efficiently.Different kinds of data structures are suited to different kinds of applications, and some are highly specialized to specific tasks...
, requiring an interpreterInterpreter (computing)In computer science, an interpreter normally means a computer program that executes, i.e. performs, instructions written in a programming language... - Duff's deviceDuff's deviceIn computer science, Duff's device is an optimized implementation of a serial copy that uses a technique widely applied in assembly language for loop unwinding. Its discovery is credited to Tom Duff in November of 1983, who at the time was working for Lucasfilm. It is perhaps the most dramatic...
- a loop unwindingLoop unwindingLoop unwinding, also known as loop unrolling, is a loop transformation technique that attempts to optimize a program's execution speed at the expense of its binary size...
technique that makes use of a switch statement. - Conditional statement - A switch statement is a type of conditional statement
- McCarthy FormalismMcCarthy FormalismIn computer science and recursion theory the McCarthy Formalism of computer scientist John McCarthy clarifies the notion of recursive functions by use of the IF-THEN-ELSE construction common to computer science, together with the four of the operators of primitive recursive functions: zero,...
- for history and historical references - Multiway branchMultiway branchMultiway branch is a computer science term used to describe the change to a program's control flow based upon a value matching a selected criteria. It is a form of conditional statement...
- a switch statement is a type of multiway branch