
C switch
The switch statement is a control flow statement that allows you to select one of many possible code blocks to execute based on the value of an expression. It provides an alternative to using multiple if-else if statements when you need to make a decision among several options.
The basic syntax of the switch statement is as follows:
switch (expression) {
case constant1:
// Code to execute if expression equals constant1
break; // Optional; used to exit the switch block
case constant2:
// Code to execute if expression equals constant2
break;
// Additional case labels as needed
default:
// Code to execute if expression does not match any case
}Here’s how the switch statement works:
- The
expressionis evaluated, and its value is compared to the constants in thecaselabels. - If a match is found, the code block associated with that
caselabel is executed. - The
breakstatement is used to exit theswitchblock after executing the code for a matchedcase. Ifbreakis not used, execution will continue into subsequentcaseblocks until abreakis encountered or theswitchblock ends. - The
defaultcase is optional and is executed when none of thecaselabels match the value of the expression. It serves as the “default” action when no specific case is met.
Here’s an example that uses a switch statement to determine the day of the week based on a numeric value:
#include <stdio.h>
int main() {
int day = 3; // Assuming 3 represents Wednesday
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;
}In this example, the value of day is compared to each case label, and the corresponding day of the week is printed. If day does not match any of the case labels, the default case is executed, indicating that it’s an invalid day.
A few key points to keep in mind when using switch:
- The
expressioninside theswitchshould evaluate to an integer or character type (e.g.,int,char,enum). - Each
caselabel must be a constant expression (e.g., integer constants, character literals, or enumeration constants). - Use
breakto exit theswitchblock when the desiredcaseis found. - The
defaultcase is optional but provides a fallback option for unmatched values. - You can have multiple
caselabels for the same block of code (fall-through behavior) if multiple cases should execute the same code.
The switch statement is a powerful control flow construct for handling multiple conditional branches efficiently and is commonly used for menu-driven programs and state machines.