Search⌘ K
AI Features

Selection with the switch statement

Explore how to use the switch statement as an alternative to if statements for selecting among multiple options based on fixed values. Learn its structure, how to manage case fallthrough with break statements, and use the default case for unmatched values. Gain insights into writing readable and maintainable code with switch constructs to handle dynamic program flow efficiently.

The switch statement

One alternative, when we have one option out of many that can be true, is the switch statement. It also works with conditions even if they aren’t as apparent as they are in an if statement.

Another difference is that a switch statement only compares values for equality. The reason for it is that it isn’t suitable for the age logic we used when we explored the if statement, because we wanted to see if the age was between two values. Instead, it’s perfect if we’re going to match it to a value that’s fixed. We’ll look at a real example soon. However, let’s first explore the structure of the switch statement.

Structure of the switch statement

What a switch statement looks like depends on what language we’re using. What we’ll see here is a structure that’s rather common, but when applying it, we’ll need to look up the correct syntax for our language.

A switch statement begins by stating what variable we want to check. It’s common for languages to use the switch keyword for this.

The structure looks something like this:

C++
switch(variable)
end_switch

In this example, the name variable is just a placeholder for the actual variable we want to work with. Between the switch keyword and end_switch, we’ll need to specify each value we want to compare the variable to. It could ...