Switch case statement consists of number of cases which upon condition match execute the statements. Switch case statement is repalcement for if .. else if .. else statement. If we have to check condition against number of cases then switch case statement is useful.
Syntax for switch case statement in C:
switch (expression or variable)
{
case expression1 or variable1:
statements;
break;
case expression2 or variable2:
statements;
break;
.
.
.
default:
statements;
}
In switch case statement if expression or variable of any case is equal to given expression or variable then the respective case is executed.
Program example of switch case statement
//An example of switch case statement
#include<stdio.h>
int main()
{
int a = 2;
switch (a)
{
case 1:
printf("case 1 is executed\n");
break;
case 2:
printf("case 2 is executed\n");
break;
case 3:
printf("case 3 is executed\n");
break;
default:
printf("No case matched\n");
}
return 0;
}
output
case 3 is executed
In the above example we have provided a variable a = 2
to the switch statement. When the switch statement finds the exact match of the variable then the control is transferred to the respective case and it starts executing the statements until the break
keyword is found. Once it find the break keyword it exit from the switch statement.