switch Statement in C
The switch statement is a cleaner alternative to long if-else chains. It checks one variable against multiple fixed values.
Syntax
c
switch (expression) {
case value1:
// code here
break; // exit switch
case value2:
// code here
break;
default: // runs if no case matches
// code here
}Simple Calculator using switch
c
#include <stdio.h>
int main() {
float a, b;
char op;
printf("Enter: number op number (e.g. 10 + 5): ");
scanf("%f %c %f", &a, &op, &b);
printf("%.2f %c %.2f = ", a, op, b);
switch (op) {
case '+': printf("%.2f\n", a + b); break;
case '-': printf("%.2f\n", a - b); break;
case '*': printf("%.2f\n", a * b); break;
case '/':
if (b != 0) printf("%.2f\n", a / b);
else printf("Error: Division by zero!\n");
break;
default:
printf("Unknown operator!\n");
}
return 0;
}▶ Output
Enter: number op number (e.g. 10 + 5): 15 * 4 15.00 * 4.00 = 60.00
switch vs if-else Comparison
| Feature | switch | if-else |
|---|---|---|
| Best for | Fixed values (int, char only) | Ranges, complex conditions |
| Speed | Faster — uses jump table | Slightly slower — checks sequentially |
| float allowed? | NO | YES |
| Readable | Very clean for many options | Gets messy with 5+ conditions |
| Fall-through | Yes — without break | No |
⚠ Warning: ALWAYS add
break; at the end of each case! Without break, execution falls through to the next case automatically — this is usually a bug.