The switch statement is a control flow statement in the C programming language that allows you to execute a block of code based on the value of a variable or expression. The syntax for a switch statement is as follows:
switch (expression) {
case value1:
// code to execute if expression equals value1
break;
case value2:
// code to execute if expression equals value2
break;
...
default:
// code to execute if expression does not match any of the case values
}
The expression is evaluated and compared to each of the case values. If a match is found, the code inside the corresponding case block is executed. If no match is found, the code inside the default block is executed (if it is included).
For example, consider the following code:
int x = 2;
switch (x) {
case 1:
printf("x is 1\n");
break;
case 2:
printf("x is 2\n");
break;
case 3:
printf("x is 3\n");
break;
default:
printf("x is not 1, 2, or 3\n");
}
In this example, the value of x (2) matches the second case value (2), so the code inside the second case block is executed and the message “x is 2” is printed to the console.
It is important to include the break statement at the end of each case block to exit the switch statement. If you omit the break statement, the code inside the following case blocks will also be executed, even if the expression does not match the corresponding case value.
For example:
int x = 2;
switch (x) {
case 1:
printf("x is 1\n");
case 2:
printf("x is 2\n");
case 3:
printf("x is 3\n");
default:
printf("x is not 1, 2, or 3\n");
}
In this example, the value of x (2) matches the second case value (2), so the code inside the second case block is executed and the message “x is 2” is printed to the console. However, because the break statement is omitted, the code inside the third case block is also executed and the message “x is 3” is printed to the console.
It is also possible to use an expression as the case value, as long as the expression can be resolved to a constant value at compile time. For example:
int x = 3;
int y = 5;
switch (x + y) {
case 4:
printf("x + y is 4\n");
break;
case 9:
printf("x + y is 9\n");
break;
default:
printf("x + y is not 4 or 9\n");
}
In this example, the expression (x + y) is evaluated as 8, which does not match any of the case values. Therefore, the code inside the default block is executed and the message “x + y is not 4 or 9” is printed to the console.