The Switch Construct
The switch statement is a multi-way decision-making construct that tests an expression matches one of a number of constant values, and branches accordingly. The switch statement is another alternative to using nested if-else statements. The general format is as follows :
switch(expression)
{
case value1 : statements;
:
:
break;
case value2 : statements;
:
:
break;
case value3 : statements;
:
:
break;
default : statements;
:
:
}
The expression must be declared in the parentheses, and the body of the switch statement must be enclosed in braces. The values with case should be constants. The expression is evaluated and compared with the values in cases; if it matches the statements under it are implemented till it encounters a break statement. If the value does not match with any of the case statements then the statements under the default label are implemented.
Omission of break takes control by the next case statements regarded whether the value of case matches or not. This can also be used constructively when similar operation has to be performed on a number of cases.
e.g.
switch(ch)
{
case 'a' :
case 'e' :
case 'i' :
case 'o' :
case 'u' : cout << "Vowel";
default : cout << " Consonant ";
}
In the above example if the value of ch is any of a,e,i,o,u then they are printed as vowels , or else they are printed as consonants