A switch statement allows a variable to be tested for equality against multiple values and each of those values is called a case. It can be used instead of nested if...else
.
Switch expression and case value must be of the same type. There must be at least one case or multiple cases with unique case values. In the end, it can have a default case which is optional that is executed if no cases are matched.
Syntax
Syntax of switch
statement in C:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | switch (expression) { case value1: //code to be executed; break; //optional case value2: //code to be executed; break; //optional . . . . case valueN: //code to be executed; break; //optional default: code to be executed if all cases are not matched; } |
Switch statement Flowchart:
Example of switch statement in C.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | #include <stdio.h> int main() { //local variable definition char grade = 'D'; switch (grade) { case 'A': printf("Excellent!\n"); break; case 'B': printf("Very Good!\n"); break; case 'C': printf("Well done\n"); break; case 'D': printf("GRADE D\n"); break; case 'F': printf("Better try again\n"); break; default: printf("Invalid grade\n"); } printf("You Pass with Grade: %c\n", grade); return 0; } |
The output of the switch statement in C.
GRADE D
You Pass with Grade: D