C Switch Statement
The switch statement in C is an alternate to if-else-if ladder statement which allows us to execute multiple operations for the different possibles values of a single variable called switch variable. Here, We can define various statements in the multiple cases for the different values of a single variable.
The syntax of switch statement in c language is given below:
Rules for switch statement in C language
1) The switch expression must be of an integer or character type.
2) The case value must be an integer or character constant.
3) The case value can be used only inside the switch statement.
4) The break statement in switch case is not must. It is optional. If there is no break statement found in the case, all the cases will be executed present after the matched case. It is known as fall through the state of C switch statement.
Let’s try to understand it by the examples. We are assuming that there are following variables.
Valid Switch | Invalid Switch | Valid Case | Invalid Case |
---|---|---|---|
switch(x) | switch(f) | case 3; | case 2.5; |
switch(x>y) | switch(x+2.5) | case ‘a’; | case x; |
switch(a+b-2) | case 1+2; | case x+2; | |
switch(func(x,y)) | case ‘x’>’y’; | case 1,2,3; |
Flowchart of switch statement in C
Functioning of switch case statement
First, the integer expression specified in the switch statement is evaluated. This value is then matched one by one with the constant values given in the different cases. If a match is found, then all the statements specified in that case are executed along with the all the cases present after that case including the default statement. No two cases can have similar values. If the matched case contains a break statement, then all the cases present after that will be skipped, and the control comes out of the switch. Otherwise, all the cases following the matched case will be executed.
Let’s see a simple example of c language switch statement.
Output
enter a number:4 number is not equal to 10, 50 or 100
enter a number:50 number is equal to 50
Switch case example 2
Output
hi
C Switch statement is fall-through
In C language, the switch statement is fall through; it means if you don’t use a break statement in the switch case, all the cases after the matching case will be executed.
Let’s try to understand the fall through state of switch statement by the example given below.
Output
enter a number:10 number is equal to 10 number is equal to 50 number is equal to 100 number is not equal to 10, 50 or 100
Output
enter a number:50 number is equal to 50 number is equal to 100 number is not equal to 10, 50 or 100
Nested switch case statement
We can use as many switch statement as we want inside a switch statement. Such type of statements is called nested switch case statements. Consider the following example.
Output
the value of i evaluated in outer switch: 10 The value of j evaluated in nested switch: 20 Exact value of i is : 10 Exact value of j is : 20