Switch statement
From Wikipedia, the free encyclopedia
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.
Contents |
[edit] Examples
The following are simple examples, written in the various languages, that use switch statements to print one of several possible lines, depending on the value of an integer entered by the user. 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=5, the second case statement will produce a match to the control variable. Since there are no statements following this line and no break keyword, execution continues through the 'case 7:' line and to the next line, which produces output. The break line after this causes the switch statement to conclude. If the user types in more than one digit, the default block is executed, producing an error message.
[edit] C
switch(n) { case 0: printf("You typed zero.\n"); break; case 3: case 5: case 7: printf("n is a prime number\n"); break; case 2: printf("n is a prime number\n"); case 4: case 6: case 8: printf("n is an even number\n"); break; case 1: case 9: printf("n is a perfect square\n"); break; default: printf("Only single-digit numbers are allowed\n"); break; }
[edit] Java
switch (n) { case 0: System.out.println("You typed zero.\n"); break; case 3: case 5: case 7: System.out.println("n is a prime number\n"); break; case 2: System.out.println("n is a prime number\n"); case 4: case 6: case 8: System.out.println("n is an even number\n"); break; case 1: case 9: System.out.println("n is a perfect square\n"); break; default: System.out.println("Only single-digit numbers are allowed\n"); break; }
[edit] Actionscript
switch (variable) { case 0: trace("case number 0 tested true"); break; case 1: trace("case supre Bold textnumber 1 tested true"); break; case 2: trace("case data number 2 tested true"); break; /** * case statements in Actionscript do not have to use numbers necessarily, * one can use matching strings or other types. */ case "A": trace("case 'A' event"); break; /** * multiple clauses can be grouped as well */ case "B","b": trace("case 'B' or 'b' event"); break; default: trace("no cases tested true"); break; } /** * Generally, its a bit more efficient to populate an array of responses and count through a series of * comparatives in a for loop, use a mathematical formula in a while loop etc. but switch can be handy * for diagnostics and are easier to read inline with code, particularly when contents of the comparative * array are populated externally. */
[edit] REALbasic
REALbasic uses a slightly different syntax for the same concept. It uses the fairly widespread BASIC syntax of select case (Dartmouth BASIC has had a statement of this kind since the mid 1970s), like so:
select case someInteger case 0 // Simple case of a single statement DoSomething case 1,2,5 // Using multiple case values DoSomethingElse case 8 to 10 // Using a range of case values DoSomethingYetAgain case Is > 20 // Using a comparison of case values OneMoreTime else // the catch-all (default) block NoMore end select
[edit] C#
C# uses a standard C style syntax with the addition of a 'goto case' statement. Strings may also be used in switch statements:
switch (someInteger) { case 0: case 1: return 1; // executed when someInteger is 0 or 1 case 2: someInteger++; goto case 3://this is incorrect, it should be (;) semi-colon, otherwise you get a compilation error. case 3: DoSomething(); break; default: DoSomethingElse(); break; }
[edit] Symbolic Constants in Switch
In many (but not all) circumstances, using names rather than ordinary integers makes the source code easier to read. This has no influence on the behaviour of the behaviour of the program. This style of switch statement is commonly used for finite state machine implementation. The tradition in C is for such constants to be in all capitals, although this is not enforced by the compiler. Here are some examples:
[edit] C (using pre-processor)
#define STATE_READY 1 #define STATE_SET 2 #define STATE_GO 3 #define STATE_FAIL 4 switch( state ) { case STATE_READY: state = STATE_SET; if( x < 0 ) state = STATE_FAIL; break; case STATE_SET: state = STATE_GO; if( y > 0 ) state = STATE_FAIL; break; case STATE_GO: printf( "go!\n" ); break; case STATE_FAIL: exit( -1 ); }
[edit] C (using enum)
enum { STATE_READY = 1, STATE_SET = 2, STATE_GO = 3, STATE_FAIL = 4, }; switch( state ) { case STATE_READY: state = STATE_SET; if( x < 0 ) state = STATE_FAIL; break; case STATE_SET: state = STATE_GO; if( y > 0 ) state = STATE_FAIL; break; case STATE_GO: printf( "go!\n" ); break; case STATE_FAIL: exit( -1 ); }
[edit] C (const int illegal in switch)
WARNING: although this example looks tempting, it will not compile in a standard C compiler. The const keyword in C is a weak sort of constant and not suitable for use as a case in a switch statement.
const int STATE_READY = 1; const int STATE_SET = 2; const int STATE_GO = 3; const int STATE_FAIL = 4; switch( state ) { case STATE_READY: state = STATE_SET; if( x < 0 ) state = STATE_FAIL; break; case STATE_SET: state = STATE_GO; if( y > 0 ) state = STATE_FAIL; break; case STATE_GO: printf( "go!\n" ); break; case STATE_FAIL: exit( -1 ); }
[edit] Alternative Uses
Many languages also support using "true" as the variable, and having an expression as the case.
For example in PHP you can do:
switch(true) { case ($x == 'hello'): foo(); break; case ($z == 'howdy'): break; }
The reason this works is because the variable being switched for is the boolean true. So having x=='hello' as a condition would either return true or false, so if that is true, it matches the thing which is being checked.
You could also use this for checking multiple variables against one value instead of checking multiple values for one variable:
//example 1: common use switch($x) { case 5: break; case 6: break; } //example 2: alternative use switch(5) { case $x: break; case $y: break; }