C switch Statement
In this page:
What is a switch Statement?
A switch statement evaluates one expression once and compares it against a list of case labels, jumping directly to the matching case -- a cleaner alternative to a long else-if ladder when you're comparing one variable against many fixed values.
Example: What is a switch Statement?
#include <stdio.h>
int main() {
int day = 3;
switch (day) {
case 3:
printf("Wednesday");
break;
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Day of the Week
Mapping the integers 1 through 7 to day names is a classic switch use case: each case label handles one specific number, making the mapping far more readable than an equivalent chain of if-else comparisons.
Example: Day of the Week
#include <stdio.h>
int main() {
int day = 2;
switch (day) {
case 1: printf("Monday"); break;
case 2: printf("Tuesday"); break;
case 3: printf("Wednesday"); break;
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Grade Switch
switch can match character constants too, so a grade switch might map the case A to print "Excellent", letting you branch on single-character input just as easily as on integers.
Example: Grade Switch
#include <stdio.h>
int main() {
char grade = 'A';
switch (grade) {
case 'A':
printf("Excellent");
break;
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
The break Keyword
Without an explicit break at the end of a case block, execution "falls through" and continues running the code in the next case as well -- a frequent source of bugs for anyone coming from a language where fall-through isn't the default.
Example: The break Keyword
#include <stdio.h>
int main() {
int x = 1;
switch (x) {
case 1:
printf("One ");
case 2:
printf("Falls through to Two");
break;
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
The default Case
The default case runs when the switch expression doesn't match any of the listed case values, functioning as a catch-all -- useful for handling unexpected input or flagging invalid values explicitly.
Example: The default Case
#include <stdio.h>
int main() {
int x = 9;
switch (x) {
case 1:
printf("One");
break;
default:
printf("Unknown value");
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: