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:
switch (expression) {
case a:
// code expression is equal to a
break;
case b:
// code expression is equal to b
break;
}
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:
123456789int 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.
Grazie per i tuoi commenti!
Chieda ad AI
Chieda ad AI
Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione
Awesome!
Completion rate improved to 3.33
Switch Statement
Scorri per mostrare il menu
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:
switch (expression) {
case a:
// code expression is equal to a
break;
case b:
// code expression is equal to b
break;
}
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:
123456789int 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.
Grazie per i tuoi commenti!