The switch() statement is used to test a variable against a list of values, called cases, and execute the code corresponding to the first matching case. It is particularly useful when you have multiple conditions based on the value of a single variable. The switch statement can be more efficient and easier to read compared to a series of if-else statements, especially when you have many possible conditions to check.
The syntax of a switch statement typically includes:
- A variable or expression being tested.
- A series of
caselabels that specify the values to compare. - A
breakstatement to exit theswitchonce a match is found. Ifbreakis omitted, execution continues to the nextcase(this is called “fall-through”).
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”);
}
Output: Wednesday