switch, case & Ternary
switch is a jump table for integer cases; the ternary operator is a compact if-else expression. Both are easy to misuse.
In plain English
switch is a row of labeled doors. The ternary is a shortcut that picks one of two paths in a single step.
switch, case labels, and break
switch selects one of several integer or character cases. Each case label must be a constant expression. Without break, execution falls through into the next case. That can be intentional, but it is a common bug. The default label handles values that match no case.
switch (choice) {
case 'a':
printf("add\n");
break;
case 'd':
printf("delete\n");
break;
default:
printf("unknown\n");
}The conditional ternary operator
The conditional operator is the only ternary operator in C: condition ? value_if_true : value_if_false. It is an expression, so it can be used inside a larger expression. Use it for short, clear choices; a full if-else is better when either branch needs multiple statements.
int fee = (age < 18) ? 0 : 100;
int larger = (a > b) ? a : b;Key takeaways
- switch works on integer and character values.
- Missing break causes fall-through.
- case labels must be constant expressions.
- The ternary operator returns one of two values.
Common pitfalls
- Forgetting break in a switch.
- Using a non-constant expression as a case label.
- Nesting ternaries until the expression is unreadable.
Key focus
- Predict switch output with and without break.
- Know which types are allowed in switch.
Quick check
1. What happens if a case has no break?
2. What does (n > 0) ? 1 : -1 evaluate to when n is 5?