In C, a switch statement is a control flow statement that allows a variable or expression to be tested against a series of values (called cases). It helps simplify multiple if-else conditions when checking for multiple possible values of a single variable.
Syntax:
switch (expression) {
case value1:
// Code to execute if expression == value1
break;
case value2:
// Code to execute if expression == value2
break;
// More cases...
default:
// Code to execute if no case matches
}
Key Points:
- switch checks the value of the expression.
- Each case corresponds to a possible value of the expression.
- The break statement ends the switch block after a matching case is found.
- The default case runs if none of the cases match the expression.
Example 1:
#include <stdio.h>
int main() {
int day = 2;
switch (day)
{
case 1:
printf("Monday");
break;
case 2:
printf("Tuesday");
break;
case 3:
printf("Wednesday");
break;
default:
printf("Invalid day");
break;
}
return 0;
}
Output:
Tuesday
Example 2:
#include <stdio.h>
int main() {
enum Day { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };
// Initialize today as Friday
enum Day today = Friday;
switch (today) {
case Monday:
printf("Start of the work week!");
break;
case Friday:
printf("End of the work week!");
break;
default:
printf("It's a regular day.");
break;
}
return 0;
}
Output:
End of the work week!