Now that we know how if
, else if
, else
work, we can write programs that have multiple outcomes. Programs with multiple outcomes are so common that C++ provides a special statement for it… the switch
statement!
A switch
statement provides an alternative syntax that is easier to read and write. However, you are going to find these less frequently than if
, else if
, else
in the wild.
A switch
statement looks like this:
switch (grade) { case 9: std::cout << "Freshman\n"; break; case 10: std::cout << "Sophomore\n"; break; case 11: std::cout << "Junior\n"; break; case 12: std::cout << "Senior\n"; break; default: std::cout << "Invalid\n"; break; }
- The
switch
keyword initiates the statement and is followed by()
, which contains the value that each case will compare. In the example, the value or expression of the switch statement isgrade
. One restriction on this expression is that it must evaluate to an integral type (int
,char
,short
,long
,long long
, orenum
). - Inside the block,
{}
, there are multiple cases. - The
case
keyword checks if the expression matches the specified value that comes after it. The value following the first case is9
. If the value ofgrade
is equal to9
, then the code that follows the:
would run. - The
break
keyword tells the computer to exit the block and not execute any more code or check any other cases inside the code block. - At the end of each switch statement, there is a
default
statement. If none of the cases aretrue
, then the code in thedefault
statement will run. It’s essentially theelse
part.
In the code above, suppose grade
is equal to 10
, then the output would be “Sophomore”.
Note: Without the break
keyword at the end of each case, the program would execute the code for the first matching case and all subsequent cases, including the default
code. This behavior is different from if
/ else
conditional statements which execute only one block of code.
Instructions
Inside pokedex.cpp, we have a switch
statement!
Let’s add 3 more cases right before default
:
case 7
that outputs “Squirtle”case 8
that outputs “Wartortle”case 9
that outputs “Blastoise”