The switch statement is a more elegant method of handling code that would otherwise require multiple if statements. The only drawback is that the conditions must all evaluate to integer types (int or char) whereas if statements may use any data type in their conditional expressions.
Syntax
- {
- case const-expr1: statements1
.
.
.
case const-exprn: statementsn
default: statementsn+1
}
expression is evaluated and tested for a match with the const-expr in each case clause. The statements in the matching case clause are executed.
Notice that each statement falls through to the next. This is the default behavior of the switch statement. The next flow diagram shows the introduction of break statements. Adding a break statement to each statement block will eliminate fall through, allowing only one case clause's statement block to be executed.
Example 1
Example 2
Notice that the code for each case may be split onto multiple lines and that it doesn't have to start on the line of the case clause itself. Again, spaces, tabs, and newlines are rarely significant in C. Also, notice that now our constant expressions are characters. Remember that the char data type is really just an 8-bit integer, so it is perfectly legal to use here.
Example 3
Line 3 is telling us to apply this specific case to channel 4, 5, 6, and 7. Line 7 allows case 3 and 8 to fall through to case 13.