- Example structure of a switch statement.
-
switch (int) {
case value1: // the statements to execute if literal
// value1 is equivalent
// optionally a break can be listed
case value2: // the statements to execute if literal
// value2 is equivalent
// optionally a break can be listed
// ...
case valueN: // the statements to execute if literal
// valueN is equivalent
// optionally a break can be listed
default: // the default statements to execute if
// none of the literal values matched
}
- Here is an example code fragment of a switch statement that will print the string value of the digits 0 through 9.
-
switch (number) {
case 0: printf("zero\n");
break;
case 1: printf("one\n");
break;
case 2: printf("two\n");
break;
case 3: printf("three\n");
break;
case 4: printf("four\n");
break;
case 5: printf("five\n");
break;
case 6: printf("six\n");
break;
case 7: printf("seven\n");
break;
case 8: printf("eight\n");
break;
case 9: printf("nine\n");
break;
default: printf("Not 0 through 9\n");
}
- Here is an example code fragment of a switch statement that switches against a char value.
-
switch(grade) {
case 'A': printf("Exellent\n");
break;
case 'B': printf("Good\n");
break;
case 'C': printf("Average\n");
break;
case 'D': printf("Below Average\n");
break;
case 'E': printf("Failed\n");
break;
default: printf("Invalid\n");
}
- Here is an example code fragment of a switch statement that shows the falling policy to the right of the colon once an equivalent
value has been found.
-
switch(grade) {
case 'A':
case 'B':
case 'C': printf("PASS\n");
break;
case 'D':
case 'F': printf("FAIL\n");
break;
default: printf("Invalid\n");
}