Selection with 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 are not 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 is not suitable for the age logic we used when we explored the if
statement, as we wanted to see whether the age was between two values. Instead, it is perfect if we're going to match it to a value that is fixed. We will soon look at a real example. However, first, let's explore the structure of a switch
statement.
What a switch
statement looks like depends on what language we use. What we will see here is a structure that is rather common, but when applying it, you will need to look up the correct syntax for your language.
A switch
statement begins by stating what variable we want to check. It is common for languages to use the switch...