Switch statement
Switch statement
Main page

Switch statement

logo
Community Hub0 subscribers
What are your thoughts?
Be the first to start a discussion here.
Be the first to start a discussion here.
Switch statement

In computer programming, a switch statement is a selection control flow mechanism that changes execution control based on the value of an expression (i.e. evaluation of a variable). A switch statement is similar to an if statement but instead of branching only on true or false, it branches on any number of values. Although the syntax varies by programming language, most imperative languages provide a statement with the semantics described here as the switch statement. Often denoted with the keyword switch, some languages use variations such as case, select, or inspect.

Sometimes, use of a switch statement is considered superior to an equivalent series of if-then-else statements because it is:

Typically, a switch statement involves:

Two main variations of the switch statement include unstructured which supports fall through and structured which does not.

For a structured switch, as in Pascal-like languages, control jumps from the start of the switch statement to the selected case and at the end of the case, control jumps to the end of the switch statement. This behaves like an if–then–else conditional but supports branching on more than just true and false values. To allow multiple values to execute the same code (avoiding duplicate code), the syntax permits multiple values per case.

An unstructured switch, as in C (and more generally languages influenced by Fortran's computed goto), acts like goto. Control branches from the start of the switch to a case section and then control continues until either a block exit statement or the end of the switch statement. When control branches to one case, but continues into the subsequent branch, the control flow is called fall through, and allows branching to the same code for multiple values.

Fall through is prevented by ending a case with a keyword (i.e. break), but a common mistake is to accidentally omit the keyword, causing unintentional fall through and often a bug. Therefore, many consider this language feature to be dangerous, and often fall through code results in a warning from a code quality tool such as lint.

Some languages, such as JavaScript, retain fall through semantics, while others exclude or restrict it. Notably, in C# all blocks must be terminated with break or return unless the block is empty which limits fall through only for branching from multiple values.

See all
User Avatar
No comments yet.