When you're checking one variable against a bunch of possible values, a long chain of else if gets messy. That's when switch shines โ cleaner, faster, and easier to read.
Basic switch Statement
You give switch an expression, and it jumps to the matching case. Each case is a possible value.
#include
int main() {
int day = 3;
switch (day) {
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
case 3:
printf("Wednesday\n");
break;
case 4:
printf("Thursday\n");
break;
case 5:
printf("Friday\n");
break;
default:
printf("Weekend!\n");
}
return 0;
}
Try it Yourself โ
break and default
Without break, execution falls through to the next case โ sometimes useful, but usually a bug. default catches anything that doesn't match a case.
#include
int main() {
char grade = 'B';
switch (grade) {
case 'A':
printf("Excellent!\n");
break;
case 'B':
printf("Good job\n");
break;
case 'C':
printf("Fair\n");
break;
default:
printf("Try harder\n");
}
return 0;
}
Try it Yourself โ
When to Use switch vs if-else
Use switch when you're testing a single variable against exact values (integers or characters). Use if-else when you need ranges (like score >= 75) or complex conditions.