In C++ programming, a Switch statement is a type of selection control mechanism used to select one choice when multiple choices are given. It can be used as an alternative of if else if structure.
Switch statements function somewhat similar to the if statement usually used for option menu selections. The switch structure contains only one expression at its beginning and multiple cases within its body. Each case consists of a statement or set of statements.
In C++, the general syntax of switch statement:
Related Articles
switch (expression)In the above syntax:
{
case label-1:
set of statements-1;
break;
case label-2:
set of statements-2;
break;
case label-3:
set of statements-3;
break;
---- ---------------
---- ---------------
default:
set of statements-n;
}
switch | It is a keyword that indicates the beginning of "switch" structure. |
expression | It is an expression that may be a single variable (or an arithmetic expression). Its returned value should be an integer or a single character. |
case | It is a keyword that is used in switch statement to match the value according to the given expression. |
label-1 ..... label-3 | They represents the labels for the each case. Every label must be unique, numeric constant or character constant value. The value returned by expression must be same as the data type of case labels |
default | It is a keyword that is used in switch structure to execute the statement ("set of statements-n;") as default if the value returned by the expression doesn't match with any case label. |