Lesson: SWITCH Statement

Explore program flow control using the SWITCH statement.

Understand how to employ comparisons to alter program flow with the 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 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. If no case statement is matched, the default case is executed (if present). Here is an example switch block:

With x = 2, the second case is executed and execution stops with the break resulting in z = 5. If X = 1, then the first case is executed, setting z = 1, and (!) the second case would be executed (no break after first case) setting z = 5 and then there would be the break, ending there. If x = 3, then the third case as well and the default case would be executed and z would be = 11 at the end of the execution. If x = 5, no case is matched so the default case would be executed and z would = 11. Here is the example code in CodingGround. Try changing the value of x as discussed here and prove that it works.
Using Strings with switch statements is similar. Assuming day is a String variable = "tuesday", here is an example:

In this example, dayNumber will  be 2 after the switch is done. Using enumerations on switch statements is another 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.


Lesson navigation: