A switch statement (or case statement) compares an expression with a series of values in a specified order and takes the action associated with the matching value. A default action can be specified, which will be taken if no match is found. In some languages, the expression must result in a scalar value, and the cases must be constant expressions. Typical syntax is: switch (expression) { case value1: //take action 1 break; case value2: //take action 2 break; case value3: //take action 3 break; default: take default action }
A switch statement (or case statement) compares an expression with a series of values in a specified order and takes the action associated with the matching value. A default action can be specified, which will be taken if no match is found. In some languages, the expression must result in a scalar value, and the cases must be constant expressions. Typical syntax is: switch (expression) { case value1: //take action 1 break; case value2: //take action 2 break; case value3: //take action 3 break; default: take default action } Switch statements can be thought of as a terser way of expressing a series of cascading if-then-else statements. In this way, they provide a natural and readable way for a programmer to express this common decision-making behaviour.