C Switch
Switch Statement
In C programming, a switch statement is a control flow structure used to execute different blocks of code based on the value of a single variable or expression. It's a more efficient and readable alternative to using multiple if-else statements for several conditions.
The switch statement selects one of many code blocks to be executed:
Syntax
switch (expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
This is how it works:
Example
#include <stdio.h>
int main() {
int day = 4;
switch (day) {
case 1:
printf("Monday");
break;
case 2:
printf("Tuesday");
break;
case 3:
printf("Wednesday");
break;
case 4:
printf("Thursday");
break;
case 5:
printf("Friday");
break;
case 6:
printf("Saturday");
break;
case 7:
printf("Sunday");
break;
}
return 0;
}
Output
Thursday
The break Keyword
1 - Loop break: Used within loops (like for, while, or do-while) to terminate the loop prematurely.
2 - Switch break: Used within a switch statement to exit the switch block prematurely.
A break can save a lot of execution time because it "ignores" the execution of all the rest of the code in the switch block.
The default Keyword
The default keyword specifies some code to run if there is no case match:
Example
#include <stdio.h>
int main() {
int day = 4;
switch (day) {
case 6:
printf("Today is Saturday");
break;
case 7:
printf("Today is Sunday");
break;
default:
printf("Looking forward to the Weekend");
}
return 0;
}
Output
Looking forward to the Weekend
Note: The default keyword must be used as the last statement in the switch, and it does not need a break.