switch case statement is another control flow decision making statement supported by C programming language. The general syntax of switch case is as follows;
switch ( expression )
The switch case construct first evaluates the expression and jumps to the case which has the same value to execute the statement. After the statement is executed, the break keyword transfers the control out from the construct. Note that if break keyword is not used the control will execute all the cases after matching ist choice.
It should be noted that expression can be any expression that evaluates to integer value. Therefore, the values associated with all cases should also be integer.
However, there may be a case wherein no case value matches to the expression outcome. In that case, the statements of default case will be executed and then control will be transferred out from the construct. It should be noted that default is optional and needs no break. In case, the outcome of expression matches no case value and there is no default case, the control will be directly transferred out from the construct without executing any statement.
One can visualize switch case as a faster version of if…else if construct. Recall the program 6.3. in which if the user enters value 2, then first two conditions will be checked and rest will be skipped. If the program is recoded using switch case then the control will directly jump to second case without evaluating first case. Program 1 shows how to recode it using switch case construct.
printf(“please enter the weekday in number “);
Program 1: Program that uses switch case statement