Switch Statement in C
The switch statement in C allows a variable to be tested for equality against a list of values, called cases. Each case has a block of code that executes when the variable matches the case value.
Syntax
switch (expression) { case value1: // Code to execute if expression == value1 break; case value2: // Code to execute if expression == value2 break; ... default: // Code to execute if no case matches }
Example
int day = 3; switch (day) { case 1: printf("Monday"); break; case 2: printf("Tuesday"); break; case 3: printf("Wednesday"); break; default: printf("Other day"); } // Output: Wednesday
How It Works
- The switch expression is evaluated once.
- Control is transferred to the case that matches the expression value.
- If a break statement is encountered, the switch terminates.
- If no case matches, the default block executes (optional).
- Without break, execution falls through to subsequent cases.
Tips
- Always use break to prevent fall-through unless intentionally desired.
- Use default to handle unexpected values.
- Switch works best with integer, char, or enum types (not floats or strings).
- Keep cases simple for readability and maintainability.
Common Mistakes
- Omitting break statements, causing unintended execution of multiple cases.
- Using data types not supported in switch (e.g., float or double).
- Placing executable code before the first case label.
- Misplacing the default block outside the switch.
Codecrown