Зміст курсу
Introduction to C++
Introduction to C++
Switch Statement
If we have a lot of conditions it’s quite difficult to combine all of them using only if and else statements. For this reason, in C++ you can use the switch
statement to define as many cases as you want. Use the following syntax:
We are evaluating here expression using switch
statement. If expression is equal to one of the possible cases
(a
or b
), we execute code in the correspending block. The keyword break
at the end of case blocks means that when code in this block is executed we go out of the switch block.
You can use as many
cases
as you want.
Let’s take a look at the example:
int weekendDay = 1; switch (weekendDay) { case 1: cout << "It's Saturday"; break; case 2: cout << "It's Sunday"; break; }
The code above prints the day of the weekend by its number. If it’s the first day (1
) the code prints "It's Saturday"
, if it’s the second day - "It's Sunday"
.
The keyword break is optional and we will describe it more later.
Дякуємо за ваш відгук!