Switch-Case Statements
The switch statement provides an efficient, clean multi-way decision alternative to long else-if ladders.
What is it?
The `switch` statement tests the value of an integer or character expression against a list of constant case labels.
Why is it used?
Compilers often optimize `switch` into a jump table in machine code, making it significantly faster than lengthy `if-else` chains.
Detailed Explanation
Rules for Switch in C:
1. Expression must evaluate to an integral type (`int` or `char`). Floats/doubles are NOT permitted!
2. Case values must be constants or literals (e.g. `case 1:` or `case 'A':`). Variables are not allowed.
3. The `break;` statement: Essential! Without `break;`, execution falls through into subsequent cases unconditionally.
4. `default:` optional fallback executed if no case matches.
Syntax Structure
Syntax Blueprint
switch (expression) {
case CONSTANT1:
// statements
break;
case CONSTANT2:
// statements
break;
default:
// fallback
}
Code Example
C Code
#include <stdio.h>
int main() {
char course_code = 'P'; // P: Python, C: C++, J: Java, E: Excel
printf("=== Course Enrollment Routing ===\n");
switch (course_code) {
case 'P':
case 'p':
printf("Selected: KLiC Advanced Python & Flask\n");
printf("Tuition: ₹2,500 | Duration: 2.5 Months\n");
break;
case 'C':
case 'c':
printf("Selected: KLiC C and C++ Programming\n");
printf("Tuition: ₹2,500 | Duration: 2.0 Months\n");
break;
case 'E':
case 'e':
printf("Selected: KLiC Advanced Excel Mastery\n");
printf("Tuition: ₹2,500 | Duration: 1.5 Months\n");
break;
default:
printf("Unknown course code '%c'. Please contact admissions.\n", course_code);
break;
}
return 0;
}
Explanation of the Code
• Grouping `case 'P':` and `case 'p':` allows case-insensitive letter matching.
• `break;` ensures execution exits the switch block.
• `default` catches invalid inputs.
Expected Output
=== Course Enrollment Routing ===
Selected: KLiC Advanced Python & Flask
Tuition: ₹2,500 | Duration: 2.5 Months
Real-World Application
Used across command parsers, game loops (processing WASD keyboard input), and protocol packet decoders.
Common Mistakes to Avoid
• Forgetting `break;` causing unintentional fall-through bugs.
• Trying to use floating-point numbers like `case 3.14:` (compilation error in C).
Quick Practice Challenge
Build a menu with choices 1, 2, 3 that prints 'Start', 'Settings', 'Exit'.
Key Takeaways
• Switch expressions must be integral types (`int`, `char`).
• Always include `break;` to terminate each case.
• Group case labels together to handle multiple inputs identically.