Professional Documents
Culture Documents
Switch
Switch
switch (expression) {
case constant1:
break;
case constant2:
break;
default:
Explanation:
expression is evaluated, and its value is compared with each case constant.
If expression matches a case constant, the code block under that case is executed until a break
statement is encountered.
break statements are crucial; without them, the execution will continue to the next case without
checking for conditions.
Example:
Copy code
#include <stdio.h>
int main() {
int choice;
scanf("%d", &choice);
switch (choice) {
case 1:
break;
case 2:
break;
case 3:
break;
default:
printf("Invalid choice\n");
return 0;
Key Points:
switch is used for multiway branching, providing a neater alternative to multiple if-else statements.
The case constants must be integral values (integers or characters) and unique within the same switch.
Each case label ends with a break statement to prevent fall-through to the next case.
The default case is optional and executes when no matching case is found.
It's important to note that the switch statement can only compare values, not conditions, and it doesn't
support comparing strings directly (prior to C99). Also, each case value should be unique; having
duplicate case values will result in a compilation error.