Case and Switch Statement

Case and switch statements are used to run conditional code based on the state of another variable. This differs from if statements, as case statements cannot use less than or more than operators, only equals operators. Case statements are used only when a variable is equal to certain state.

Think of a store owner and someone asking them if they stock a certain product. Depending on the product the shop owner may have to go to a different shelf or cupboard. A switch statement only compares one variable, it cannot contain multiple variable checks.

The below code shows a simple example of a switch statement based on our shop owner example.

The break words within the switch statements make the program exit out of the entire switch statement. Without the break keywords the code would fall through to the next code to be executed. For example, if we removed the break in the ‘eggs’ case then the code within the ‘spice’ case would also be executed.

The default case is an optional statement. The code within the default case will only be executed if no other cases are executed. If our product was equals to “milk” then the default case would be executed, as we don’t have a another case that matches that criteria.

Leave a Reply