switch

Allows a program to evaluate an expression and attempt to match the expression's value to a case label.

Syntax

switch ( expression )
{
case label :
statements;
break;
case label :
statements;
break;
...
default : statements;
}

Parameters

Parameter Description
expression Value matched against label.
label Identifier used to match against expression.
statements Block of statements that is executed once if expression matches label.

Description

If a match is found, the program executes the associated statement. If multiple cases match the provided value, the first case that matches is selected, even if the cases are not equal to each other.

The program first looks for a label matching the value of expression and then executes the associated statement. If no matching label is found, the program looks for the optional default statement, and if found, executes the associated statement. If no default statement is found, the program continues execution at the statement following the end of switch.

The optional break statement associated with each case label ensures that the program breaks out of switch once the matched statement is executed and continues execution at the statement following switch. If break is omitted, the program continues execution at the next statement in the switch statement.

Examples

In the following example, if expression evaluates to "Bananas", the program matches the value with case "Bananas" and executes the associated statement. When break is encountered, the program breaks out of switch and executes the statement following switch. If break were omitted, the statement for case "Cherries" would also be executed.

Enter labels to add to this page:
Please wait 
Looking for a label? Just start typing.