Switch Statement in C: Syntax and Examples
What is a Switch Statement?
The switch statement is used to execute one block of code among many alternatives, based on the value of a variable.
Syntax
switch (expression) {
case value1:
// code
break;
case value2:
// code
break;
default:
// code
}
Example
int day = 3;
switch (day) {
case 1: printf("Monday"); break;
case 2: printf("Tuesday"); break;
case 3: printf("Wednesday"); break;
default: printf("Invalid day");
}
Key Points
- The
breakstatement prevents fall-through to the next case. switchworks only with integer or character constant expressions.defaultruns when no case matches, and is optional.
PreviousConditional Statements in C: if, if..else, Nested if
Next Understanding do...while loop in C
Ready to master real-world C Programming development?
Learn C Programming hands-on with mentor-led, live sessions.
.png)