C switch-case Statement – A Smart Alternative to else-if Ladder
The switch-case
statement in C is used to execute different blocks of code based on the value of a variable or expression. It’s a great alternative to using multiple else-if
statements, especially when you’re checking for equality against constants.
Syntax of switch-case
switch(expression) {
case constant1:
// Code block 1
break;
case constant2:
// Code block 2
break;
...
default:
// Default code block
}
Key Points:
The
expression
is evaluated once.The result is compared to each
case
.The
break
statement prevents fall-through.The
default
block runs if nocase
matches.
Example 1 – Simple Menu
#include <stdio.h>
int main() {
int choice;
printf("1. Add\n2. Subtract\n3. Multiply\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("You chose Add.\n");
break;
case 2:
printf("You chose Subtract.\n");
break;
case 3:
printf("You chose Multiply.\n");
break;
default:
printf("Invalid choice.\n");
}
return 0;
}
Output:
1. Add
2. Subtract
3. Multiply
Enter your choice: 2
You chose Subtract.
Example 2 – Days of the Week
#include <stdio.h>
int main() {
int day = 4;
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;
case 6:
printf("Saturday\n");
break;
case 7:
printf("Sunday\n");
break;
default:
printf("Invalid day\n");
}
return 0;
}
When to Use switch-case
Use when:
Comparing one variable to many constant values
You want clearer, faster code than an
if-else-if
chain
Avoid When:
Comparing ranges or complex conditions
Working with non-integer types (in older C versions)
Common Mistakes
Mistake | Why It’s a Problem |
---|---|
Forgetting break | Causes fall-through to the next case |
Using variables in case | Only constant expressions are allowed |
Skipping default | May miss handling unexpected values |
Best Practices
Tip | Benefit |
---|---|
Always use break unless fall-through is needed | Avoids bugs and confusing behavior |
Include a default case | Handles unknown inputs safely |
Indent properly for readability | Cleaner and more understandable code |