c / beginner
Snippet
The Switch Statement
The switch statement is an alternative to long if-else chains. It compares a variable against multiple 'case' values and executes the matching block.
snippet.c
1
2
3
4
5
6
7
8
9
10
switch (grade) {case 'A':printf("Excellent!\n");break;case 'B':printf("Good job!\n");break;default:printf("Keep trying.\n");}
Breakdown
1
switch (grade) {
Starts the evaluation of the variable 'grade'.
2
case 'A':
Defines a block of code to run if grade equals 'A'.
3
break;
Exits the switch block so it doesn't run the next cases.