Switch Statement in C
Switch statement in C allows you to work with multiple option type problems. When you have to choose only one choice from multiple choices in that case switch statements can be used. Switch statement is a setup of many cases in it.
In switch block the result of the expression or condition given is compared with the values in the different cases. If the value matches then that particular case alone is evaluated. If there is no match then the default block given will be executed.
Syntax
switch(expression)
{
case value-1:
block-1;
break;
case value-2:
block-2;
break;
case value-3:
block-3;
break;
default:
default-block;
break;
}
Rules for switch statement
- The result of the expression must be an integer value.
- The case label values must be unique and it should end with a colon(:).
- The line after the case statement can be any valid C statement.
Example
#include <stdio.h>
int main()
{
int a = 3;
switch (a)
{
case 1: printf("Choice is 1");
break;
case 2: printf("Choice is 2");
break;
case 3: printf("Choice is 3");
break;
default: printf("No Choice");
break;
}
return 0;
}
Output
Choice is 3
Note: If there is no break statements in each case then all the cases will be executed.