C - Switch Statement
switch selects a branch based on the value of an integral expression (e.g., int, char). Use it when comparing a single variable to many constants.
Learning Objectives
- Use
switchwithcase,break, anddefault. - Understand fall-through and when it’s intentional.
Prerequisites
Example
#include <stdio.h>
int main(void) {
char op = '+';
int a = 2, b = 3, result = 0;
switch (op) {
case '+': result = a + b; break;
case '-': result = a - b; break;
case '*': result = a * b; break;
case '/': result = (b != 0) ? a / b : 0; break;
default: printf("unknown op\n"); break;
}
printf("%d\n", result);
}
Common Pitfalls
- Missing
breakcauses fall-through into the next case. - Using non-integral types in
switchexpressions (not allowed in C).
Checks for Understanding
- What does the
defaultlabel do?
Show answers
- Handles any case not matched by the listed
caselabels.