Selection with the switch statement
Learn how statements are selectively executed based on the switch statement.
We'll cover the following...
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:
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 ...