A switch statement allows a variable to be tested against several values for equality. Each of these values is called a case. Once a matching case is found, its particular block of code is executed. It is an alternative to the more common if-else statement.
switch(expression)
{
case constant_1 :
// Code to be executed if expression == constant_1
break;
case constant_2 :
// Code to be executed if expression == constant_2;
break;
default : // the default case is optional
// Code to be executed if none of the cases match.
}
There are some rules to keep in mind while writing switch statements:
expression
in the switch can be a variable or an expression - but it must be an integer or a character.default
case is executed when none of the cases above match.break
statement is used to break the flow of control once a case block is executed. While it is optional, without it, all subsequent cases after the matching case will also get executed. Consider the code below to get a clearer idea:The following diagram illustrates the flow of control in a switch:
Since var = 10
, the control jumped to the case 10
block - but without any breaks, the flow is not broken and all subsequent case statements are also printed.
Try uncommenting the break
statements and note the output. Feel free to experiment with the value of var
as well.
Note: A
break
is not needed after thedefault
case. This is because control would naturally exit theswitch
statement anyway.
int main() {int var = 10;switch (var){case 5:printf("Case 1 executed.");// break;case 10:printf("Case 2 executed. ");// break;case 15:printf("Case 3 executed. ");// break;case 20:printf("Case 4 executed. ");// break;default:printf("Default case executed. ");}}
You can use char
's for the switch expression and cases as well. In the code below, option
matches case 'b'
, hence its case block is executed.
int main() {char option = 'b';switch (option){case 'a':printf("Case a hit.");break;case 'b':printf("Case b hit. ");break;case 'c':printf("Case c hit. ");break;default:printf("Default case hit.");}}
Free Resources