Switch Statement in C: Rules For Using Statement
Switch Statement in C: Rules For Using Statement
When you want to solve multiple option type problems, for example: Menu like
program, where one value is associated with each option and you need to choose
only one at a time, then, switch statement is used.
Switch statement is a control statement that allows us to choose only one choice
among the many given choices. The expression in switch evaluates to return an
integral value, which is then compared to the values present in different cases. It
executes that block of code which matches the case value. If there is no match,
then default block is executed(if present). The general form of switch statement is,
switch(expression)
{
case value-1:
block-1;
break;
case value-2:
block-2;
break;
case value-3:
block-3;
break;
case value-4:
block-4;
break;
default:
default-block;
break;
}
Points to Remember
1. We don't use those expressions to evaluate switch case, which may return
floating point values or strings or characters.
2. break statements are used to exit the switch block. It isn't necessary to
use break after each block, but if you do not use it, then all the consecutive
blocks of code will get executed after the matching block.
3. int i = 1;
4. switch(i)
5. {
6. case 1:
7. printf("A"); // No break
8. case 2:
9. printf("B"); // No break
10. case 3:
11. printf("C");
12. break;
}
A B C
The output was supposed to be only A because only the first case matches,
but as there is no break statement after that block, the next blocks are
executed too, until it a break statement in encountered or the execution
reaches the end of the switch block.
Example of switch statement
#include<stdio.h>
void main( )
{
int a, b, c, choice;
while(choice != 3)
{
/* Printing the available options */
printf("\n 1. Press 1 for addition");
printf("\n 2. Press 2 for subtraction");
printf("\n Enter your choice");
/* Taking users input */
scanf("%d", &choice);
switch(choice)
{
case 1:
printf("Enter 2 numbers");
scanf("%d%d", &a, &b);
c = a + b;
printf("%d", c);
break;
case 2:
printf("Enter 2 numbers");
scanf("%d%d", &a, &b);
c = a - b;
printf("%d", c);
break;
default:
printf("you have passed a wrong key");
printf("\n press any key to continue");
}
}
}
Difference between switch and if
evaluate float conditions.
if statement can evaluate relational operators. switch statement cannot