Unlike the If statement which allows a selection of two alternatives the switch statement allows a program to select one statement for execution out of a set of alternatives.
During execution of switch statement only one of possible statements will be executed, remaining statements will be skipped.
The usage of multiple If else statement increases complexity of program since when number of If else statements increase it affects the readability of program & makes it difficult to follow program.
Switch statement removes these disadvantages by using a simple & straight forward approach.
The Switch Statement
Switch (expression)
{
Case case-label-1;
Case case-label-2;
Case case-label-n;
Case default
}
Syntax description
When the switch statement is executed the control expression is evaluated first and the value is compared with the case label values in the given order.
If the label matches with the value of the expression then the control is transferred directly to the group of statements which follow the label.
If none of the statements matches then the statement against the default is executed.
Default statement is optional in switch statement in case if any default statement is not given and if none of the condition matches then no action takes place in this case the control transfers to the next statement of the if else statement.