When a program needs to choose between multiple options, writing many if-else statements can become difficult to manage. In such cases, C provides the switch statement for cleaner and more organized decision-making.
The switch statement compares a variable or expression against multiple cases and executes the matching block of code.
switch Syntax
The switch statement compares an expression's value against multiple unique case labels and branches execution to the matching case block.
switch(expression)
{
case value1:
// code executes if expression == value1
break;
case value2:
// code executes if expression == value2
break;
default:
// code executes if no cases match
}
Example Program
#include <stdio.h>
int main()
{
int day = 3;
switch(day)
{
case 1:
printf("Monday");
break;
case 2:
printf("Tuesday");
break;
case 3:
printf("Wednesday");
break;
default:
printf("Invalid Day");
}
return 0;
}
Program Flowchart
Console Output
Wednesday
How It Works
The expression inside switch() is evaluated first. The program then checks each case value one by one. When a matching case is found, the corresponding block of code executes.
The break statement stops execution after the matching case. Without break, execution continues into the next case, which is called fall-through behavior. The default block executes when none of the cases match.
Key Points
To master the switch statement, remember these essential design rules:
switchis extremely useful for handling multiple fixed, discrete conditions rather than ranges.- Each
casevalue must be a unique, constant expression (like integers or char literals). - The
breakstatement prevents fall-through execution into subsequent cases. - The
defaultcase is optional but highly recommended to catch unexpected or invalid input states.
Embedded Focus
Switch statements are widely used in embedded systems for menu handling, communication protocols, device states, and command processing.
switch(command)
{
case 1:
led_on();
break;
case 2:
led_off();
break;
}
In embedded programming, switch statements help organize multiple hardware operations and state machines in a highly efficient and clean way.