When decision from a number of choices is required, at that time switch-case default is used.
A switch statement
allows a variable to be tested for equality against a list of values. Each
value is called a case, and the variable being switched on is checked for each switch case.
Syntax for the switch - case structure is as follows :
Switch ( integer expression)
{
case value1 : action1 ;
case value2 : action2 ;
default : action3 ;
}
First the expression is evaluated.
After getting the value it is matched one by one with constant
values in case statements.
When a match is found, it executes the statements following that
case and all subsequent case and default statements as well.
Execution of the Switch:
- Integer expression is any constant or expression that evaluates to an integer.
- The keyword case is followed by an integer or a character constant.
- Float is not allowed as case value.
- Each constant in each case must be different from all others.
Notes while using the Switch:
- Order is not important while putting the case values.
- No enclosure is needed in case statements.
- break statement must be used to prevent the execution of subsequent cases.
- Use of continue will not take the control to beginning of switch.
Switch & if-else:
Switch is a better way of writing programs.
In certain situations switch is not useful.
Example : i <= 20
More structured program in switch
0 comments :