A switch statement in C is a control structure used to execute one block of code from multiple options based on the value of an expression. It simplifies complex conditional statements like multiple if-else
blocks.
Syntax:
Key Points:
- Expression: The
switch
evaluates an integer or character expression. - Cases: Each
case
represents a possible value for the expression. - Break Statement: Used to exit the
switch
block. Withoutbreak
, execution continues to the next case (fall-through behavior). - Default Case: Executes if no matching
case
is found (optional but recommended).
Example:
Output:
Key Benefits:
- Easier to read and maintain than multiple
if-else
statements. - Efficient for handling multiple fixed values.
Limitations:
- Cannot evaluate ranges or complex conditions (use
if-else
for that). - The expression must evaluate to an integer or character type.
The switch
statement is a powerful tool for managing multi-condition branching in C programs.