Instructional Material: SWITCH Statement
The switch statement allows you to compare a value to a list of possible matching values and so select from multiple possible statements or blocks. A key difference from the if statement is that the value compared is not boolean, but instead numeric, enumeration (discussed later) or String. The form of the switch statement is:
This basic form of switch evaluates an expression resulting in a numeric value. That value is checked against the case statement values and if there is a match, the statement(s) following the case are executed. Note that execution continues into the following case statements unless the list of statements to execute is terminated by a break statement. The break statement ends a case block and execution continues with the first statement after the switch block. Most of the time each case will end with a break but there may be situations where you want case 2 executed in addition to case 1 (for example). If no case statement is matched, the default case is executed (if present). Here is an example switch block:
In this example, dayNumber will be 2 after the switch is done. Using enumerations on switch statements is another powerful form but will be discussed in a later section.
Here is a video about switch. Here is a detailed discussion of switch. Here is this example in CodingGround. Complete and test the example in CodingGround for the full 7 days of the week.
In robotics, switch can be useful to match information from controllers and sensors that is numeric in nature to actions to be taken. For instance, joysticks may return which button is pressed as a numeric value. A switch statement can match the button numbers to actions.