Previous | Home | Next |
Decision using switch
The control statement that allows us to make a decision from the number of choices is called "switch". the switch is look as following:
switch ( integer expression ) { case constant 1 : do this ; case constant 2 : do this ; case constant 3 : do this ; default : do this ; }
we can take an example of the switch case to understand easily it in deep.
main( ) { int i = 2 ; switch ( i ) { case 1 : printf ( "I am in case 1 \n" ) ; case 2 : printf ( "I am in case 2 \n" ) ; case 3 : printf ( "I am in case 3 \n" ) ; default : printf ( "I am in default \n" ) ; } } The output of this program would be: I am in case 2 I am in case 3 I am in default
Use of switch with decision control statement
- Every statement in a switch must belong to some case or the other.
- we can also use char values in case and switch.
- If we have no default case, then the program simply falls through the entire switch and continues with the next instruction (if any,) that follows the closing brace of switch.
- switch is a replacement for 'if' because it offers a better way of writing program as compared to if.
- The advantage of switch over if is that it leads to a more structured program and the level of indentation is manageable, more so if there are multiple statements within each case of a switch.
- The break statement when used in a switch takes the control outside the switch. However, use of continue will not take the control to the beginning of switch as one is likely to believe.
Switch versus if-else ladder
- A float expression cannot be tested using a switch.
- Cases can never have variable expressions (for example it is wrong to say case a +3 : ).
- Multiple cases cannot use same expressions. Thus the following switch is illegal:
switch ( a ) { case 3 : ... case 1 + 2 : ... }
Previous | Home | Next |