- [Narrator] C++ provides a special
multi-way conditional using the switch statement.
This is a feature from the C language.
Here's a working copy of switch.cpp
from chapter two of the exercise files.
Let's take a look first at how this works.
You notice that I've declared four constants.
They're integers and I call them
iONE, iTWO, iTHREE and iFOUR
and they have the values
of one, two, three and four respectively.
And I've declared another integer called X
which has a value of three.
And now I have this switch statement
which has a number of different options.
You notice it has case clauses,
case iONE, case iTWO
and wherever X matches
one of these constants,
that block of code will be executed
up until it hits the break statement.
And we'll talk more about break later on in this chapter.
A break is a branching statement that breaks out of a block.
So when it sees break, it comes down here
to the matching curly brace.
The one that matches the one at the top.
So there's all of this as a block and the break will break
out of the block and continue execution after.
And then you notice there's also a default.
If X doesn't match any of the constants,
then default is executed
and all of these have to have a break.
Otherwise, the execution will fall through to the next one
and it will execute both of them.
And so let's go ahead and run this build and run.
You notice that it says three.
And so that's because X is three and it matches iTHREE
which is declared up here on line eight.
And so that says puts three,
the string T H R E E and then break.
And if I take this break out
it'll print both three and four, watch.
Because it falls through.
And so it's good to understand that.
Occasionally you might use it,
but for the most part when you see a switch statement,
you'll see breaks after each of the cases.
Switch can be very handy
in cases where you need to select a condition
from a list of possibilities.
The case clause requires a constant.
So you'll need to take special care
to use the proper type for this purpose.
The multi-way switch control is inherited from C
although there is different restrictions
on the case clause in C.