switch case Statement in C
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 )
{
case value1:
statement1;
break;
case value2:
statement2;
break;
.
.
.
case valuen:
statementn;
break;
default:
statementx;
}
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.
#include <stdio.h>
void main()
{
int weekday;
printf(“please enter the weekday in number “);
scanf(“%d”, &weekday);
switch (weekday)
{
case 1:
puts(“Monday”);
case 2:
puts(“Tuesday”);
case 3:
puts(“Wednesday”);
case 4:
puts(“Thursday”);
case 5:
puts(“Friday”);
case 6:
puts(“Saturday”);
case 7:
puts(“Sunday”);
default:
puts(“Wrong weekday”);
}
Program 1: Program that uses switch case statement