In C, the switch statement is a multi-way decision that tests the switch expression against the number of case statements. If one of the case statement matches with switch expression, then that particular case block will be executed until the break statement. Otherwise the control of program passes to the default statement and executes the block of code. The default is optional, if it does not used, and none of the cases match, the switch statement will not perform any action. It is similar to if else if ladder statement. The syntax of the switch case statement is given below.
switch(expression) { case conts1 : Statement; break; case conts2 : Statement; break; case conts3 : Statement; break; case conts4 : Statement; break; default : statement; }
Example C Program for switch case statement
#include <stdio.h> #include <conio.h> int main() { int A=10; switch(A){ case 5 : printf("The value is 5 \n"); break; case 10 : printf("The value is 10 \n"); break; case 15 : printf("The value is 15 \n"); break; default : printf("The value is invalid \n"); break; } return(0) }
Output:
The value is 10
The break statement is used to terminate the switch case statement. The break statement is not must, if it is not used in switch case statement, then all the cases after the matching case will be executed. This is called as fall through in switch statement.
Example C Program for switch case without break statement
#include <stdio.h> #include <conio.h> int main() { int A=10; switch(A){ case 5 : printf("The value is 5 \n"); case 10 : printf("The value is 10 \n"); case 15 : printf("The value is 15 \n"); default : printf("The value is invalid \n"); } return(0) }
Output:
The value is 10 The value is 15 The value is invalid
Difference between switch and if else if ladder
switch | if else if ladder |
---|---|
Execute the block of code based on the expression match inside the switch statement | Execute block of code based on the output of the expression inside if statement. |
It only works on integer and character data type as expression is constant | It works on all data types such as integer, character, pointer or floating point and logical condition. |
Based on the value of the switch expression, the control jumps to the corresponding case | The control goes through the every else if statement until it finds true value of the statement or it comes to the end of the else if ladder. |
It works on the basis of equality operator | It works on the basis of boolean value(true or false) |
It is easy to edit and works much faster than if else if ladder | It is difficult to edit and works slower |
Each case is independent . So it directly executes the particular case on the basis of expression match. | The code needs to be processed in the order determined by the programmer. |
It requires less compilation time | It requires more compilation time |