Switch Statements

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.


switch (expression)
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.

© 2024 Microchip Technology, Inc.
Notice: ARM and Cortex are the registered trademarks of ARM Limited in the EU and other countries.
Information contained on this site regarding device applications and the like is provided only for your convenience and may be superseded by updates. It is your responsibility to ensure that your application meets with your specifications. MICROCHIP MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED, WRITTEN OR ORAL, STATUTORY OR OTHERWISE, RELATED TO THE INFORMATION, INCLUDING BUT NOT LIMITED TO ITS CONDITION, QUALITY, PERFORMANCE, MERCHANTABILITY OR FITNESS FOR PURPOSE. Microchip disclaims all liability arising from this information and its use. Use of Microchip devices in life support and/or safety applications is entirely at the buyer's risk, and the buyer agrees to defend, indemnify and hold harmless Microchip from any and all damages, claims, suits, or expenses resulting from such use. No licenses are conveyed, implicitly or otherwise, under any Microchip intellectual property rights.