Switch statement

Switch statement

In computer programming, a switch statement is a type of control statement that exists in most modern imperative programming languages (e.g., Pascal, 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 languages, 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 include C#, in which fallthrough is not permitted unless the block is empty and all blocks must be terminated via a break, or by using another keyword. Similarly, almost all BASIC dialects that feature this type of statement do not allow fallthrough.

Optimized switch

If the range of input values is identifiably 'small' and has only a few gaps, some compilers that incorporate an optimizer may actually implement the switch statement as a branch table or an array of indexed function pointers instead of a lengthy series of conditional instructions - which can be much faster. Normally, the only method of finding out if this optimization has happened is by actually looking at the resultant assembler or machine code output that has been generated by the compiler. The first 'C' example below would be eligible for this kind of optimization if the compiler supported it.

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 third 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.


=C=

switch(n) { case 0: printf("You typed zero. "); break; case 1: case 9: printf("n is a perfect square "); break; case 2: printf("n is an even number "); case 3: case 5: case 7: printf("n is a prime number "); break; case 4: printf("n is a perfect square "); case 6: case 8: printf("n is an even number "); break; default: printf("Only single-digit numbers are allowed "); break;}


=Python=

Python doesn’t have the “fall through” mechanism; a function per case is needed, and hashing is used to determine which function is called.

switch = {}switch [0] = TypedZeroFuncswitch [1] = PerfectSquareFuncswitch [2] = PrimeNumberFuncswitch [3] = PrimeNumberFuncswitch [4] = PerfectSquareFuncswitch [n] ()


=Ruby=

Ruby doesn’t have the “fall through” mechanism; it also uses case instead of switch, when instead of case and else instead of default.

case nwhen 0 then puts 'You typed zero'when 1, 9 then puts 'n is a perfect square'when 2 then puts 'n is a prime number' puts 'n is an even number'when 3, 5, 7 then puts 'n is a prime number'when 4, 6, 8 then puts 'n is an even number'else puts 'Only single-digit numbers are allowed'end

Haskell

Haskell's case construct is different in three ways: unlike C-influenced languages, it has no fall-through behaviour; it is an expression which returns a value; and it can deconstruct values using pattern matching.

case list of (f:r) -> "Not empty, first item is " ++ show f [] -> "List is empty!"


=Java=

switch (n){ case 0: System.out.println("n was Zero"); break; case 1: case 9: System.out.println("n is a perfect square"); break; case 2: case 4: case 6: case 8: System.out.println("n is an even number"); break; /* Etc. */ default: System.out.println("The default output if "n" is not a case"); break;}

ymbolic Constants in Switch

In many (but not all) circumstances,using names rather than ordinary integers makesthe source code easier to read. This has no influenceon the behavior 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:

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! " ); break; case STATE_FAIL: exit( -1 );}

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! " ); break; case STATE_FAIL: exit( -1 );}

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 constantand 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! " ); break; case STATE_FAIL: exit( -1 );}

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 useswitch($x) { case 5: break; case 6: break;}//example 2: alternative useswitch(5) { case $x: break; case $y: break;}

In Ruby, due to its handling of = equality, the statement can be used to test for variable’s class:

case inputwhen Array: puts 'input is an Array!'when Hash: 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

Compilation

If the constants form a compact range then a switch statement can be implemented very efficiently as if it were a choice based on whole numbers. This is often done by using a jump table.

Advantages and disadvantages

In some languages and programming environments, a case or switch statement is considered easier to read and maintain than an equivalent series of "if-else" statements, because it is more concise. However, when implemented with fall-through, switch statements are a frequent source of bugs among programmers new to the switch statement.

Alternatives

One alternative to a switch statement can be the use of a lookup table 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 (this is one way to implement switch statements in Lua which has no built-in switch [ [http://lua-users.org/wiki/SwitchStatement Switch statement in Lua] ] ).

In some cases, lookup tables are more efficient than switch statements as many languages can optimize the table lookup whereas switch statements are often not optimized that muchFact|date=October 2008.

Another "alternative" to switch statements is the extensive use of polymorphism.

References

See also

*Branch table an extremely fast, optimized form of a switch statement used mostly in Assembler languages
*Duff's device is a loop unwinding technique that makes use of a switch statement.
*A switch statement is a type of conditional statement.


Wikimedia Foundation. 2010.

Игры ⚽ Нужна курсовая?

Look at other dictionaries:

  • Switch-technology — is a technology for automata based programming support. It was proposed by Anatoly Shalyto in 1991. It involves software specification, design, implementation, debugging, documentation and maintenance. The term “automata based programming” is… …   Wikipedia

  • Statement (programming) — In computer programming a statement can be thought of as the smallest standalone element of an imperative programming language. A program is formed by a sequence of one or more statements. A statement will have internal components (eg,… …   Wikipedia

  • Switch (disambiguation) — NOTOC Switch may mean: Technology * Switch, or (more formally) Electromechanical switch or Electric switch, all meaning a device for making or breaking an electric circuit, or for selecting between multiple circuits; in usage the former… …   Wikipedia

  • Statement veracity analysis — There are three principal disciplines of Statement Veracity Analysis.1) Criteria Based Content Analysis ( CBCA)2) Statement Content Analysis ( SCAN ) ª3) Scientific Content Analysis ( SCAN )The study of Statement Analysis is the study of Verbal… …   Wikipedia

  • Switch file — The Fusebox switch file fbx switch.cfm, in the Fusebox computer programming language, decides which fuses to call to accomplish the requested fuseaction. It is basically a CFSWITCH statement on the fuseaction variable with one or more CFLINCLUDEs …   Wikipedia

  • Loop-switch sequence — A loop switch sequence is a specific derivative of the spaghetti code programming antipattern where a clear set of steps is implemented as a byzantine switch within a loop. Also known as The FOR CASE paradigm… …   Wikipedia

  • Sense switch — A sense switch or program switch, is a switch on the console of a computer whose state can be tested by conditional branch instructions in software. Most early computers had several sense switches. They were typically used by the operator to set… …   Wikipedia

  • C syntax — The syntax of the C programming language is a set of rules that specifies whether the sequence of characters in a file is conforming C source code. The rules specify how the character sequences are to be chunked into tokens (the lexical grammar) …   Wikipedia

  • C Sharp syntax — The correct title of this article is C# syntax. The substitution or omission of the # sign is because of technical restrictions. Main article: C Sharp (programming language) This article describes the syntax of the C# programming language. The… …   Wikipedia

  • Comparison of C Sharp and Java — The correct title of this article is Comparison of C# and Java. The substitution or omission of the # sign is because of technical restrictions. Programming language comparisons General comparison Basic syntax Basic instructions …   Wikipedia

Share the article and excerpts

Direct link
Do a right-click on the link above
and select “Copy Link”