The switch statement in C provides multi-way branching based on the value of an integral expression. The general syntax follows this structure:
switch (expression) {
case constant_1:
statements;
break;
case constant_2:
statements;
break;
default:
statements;
}
The controlling expression must evaluate to an integer-compatible type (including char or enumerated types), while each case label must be a compile-time constant integer expression. Execution begins by evaluating the expression and comparing it against each case constant. When a match is found, control transfers to that case label and proceeds sequentially through subsequent statements.
Unlike conditional structures that inherently isolate branches, switch exhibits fall-through behavior: once a matching case is found, execution continues through all following cases until encountering a break statement or the closing brace of the switch block. The optional default label executes when no case constants match the expression value.
This lack of implicit boundary protection between cases requires careful placement of break statements to prevent unintended execution. Consider the following demonstration:
#include <stdio.h>
int main(void) {
int number = 9;
int result;
switch (number % 3) {
case 0:
result = 5;
case 1:
result = 15;
break;
case 2:
result = 25;
}
return 0;
}
In this example, number % 3 evaluates to 0, causing entry into the first case where result is assigned 5. However, without a terminating break, execution falls through into case 1, overwriting result with 15. To achieve the expected value of 5, a break statement must be inserted immediately following the assignment in case 0.
While necessitating explicit exit statements adds syntactic overhead, this architecture enables multiple cases to share common execution paths by deliberately omitting breaks between them, facilitating code reuse across related conditions.