Switch Statement
The switch statement in C is another way to make decisions in your program. It is often used when you have many specific values to check against the same variable. It can make your code cleaner than using many else-if statements.
Syntax:
switch (expression) {
case value1:
// code block
break;
case value2:
// code block
break;
...
default:
// default code block
}
Example:
#include <stdio.h>
int main() {
int day = 3;
switch (day) {
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
case 3:
printf("Wednesday\n");
break;
case 4:
printf("Thursday\n");
break;
case 5:
printf("Friday\n");
break;
case 6:
printf("Saturday\n");
break;
case 7:
printf("Sunday\n");
break;
default:
printf("Invalid day\n");
}
return 0;
}
How it Works:
- The expression inside
switch()is evaluated. - The program checks each
caseto find a match. - When a match is found, that code block runs.
- The
breakstatement stops the switch from running the next cases. - If no cases match, the
defaultblock (if present) will run.
When to Use switch:
- When you want to compare a single variable to many constant values
- When
if-elsechains become long and hard to read