In computer programming, a switch statement is a type of control statement that exists in most modern imperative programming languages (e.g., C, C++, C#, and Java). Its purpose is to allow the value of a variable or expression to control the flow of program execution. In some other programming language, a statement that is syntactically different but conceptually the same as the switch statement is known as a case statement or a select statement.
In most languages, a switch statement is defined across many individual statements. A typical syntax is that the first line contains the actual word "switch" followed by either the name of a variable or some other expression allowed by the language's syntax. This variable or expression is usually referred to as the "control variable" of the switch statement. After this line, following lines define one or more blocks of code that represent possible branches that program execution may take.
Each block begins with a line containing the case keyword followed a value that the control variable may have. If the value of the control variable matches this value, program execution will jump to that block of code. If not, the value specified in the next block (if present) is examined and the process repeats.
An optional special block is also allowed, which does not specify any value and which begins with the default keyword instead of the case keyword. If this block is present and if none of the values listed for any other block matches that of the control variable, program execution will jump to the statement following the default keyword.
The method of terminating a block is also of note. Typically, a break keyword is used to signal the end of the block. When encountered, this keyword causes program execution to continue with the first statement after the series of statements within the switch statement, thus completing execution of the switch statement. If no break keyword is present at the end of the block, in many languages program execution "falls through" to the code associated with the next block in the switch statement, as if its value also matched the value of the control variable. Notable exceptions are C#, in which non-explicit fallthrough is not permitted and all blocks must be terminated via a break or other keyword, and almost all BASIC dialects that feature such a statement, where fallthrough is never permitted.
switch (someInteger) { case 0: case 1: return 1; // executed when someInteger is 0 or 1 case 2: someInteger++; goto case 3: case 3: DoSomething(); break; default: DoSomethingElse(); break; }
This article is licensed under the GNU Free Documentation License.
It uses material from the
"Switch statement".
Home Page • arts • business • computers • games • health • hospitals • home • kids & teens • news • physicians • recreation• reference • regional • science • shopping • society • sports • world