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
casesas 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.
Kiitos palautteestasi!
Kysy tekoälyä
Kysy tekoälyä
Kysy mitä tahansa tai kokeile jotakin ehdotetuista kysymyksistä aloittaaksesi keskustelumme
Kysy minulta kysymyksiä tästä aiheesta
Tiivistä tämä luku
Näytä käytännön esimerkkejä
Awesome!
Completion rate improved to 3.7
Switch Statement
Pyyhkäise näyttääksesi valikon
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
casesas 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.
Kiitos palautteestasi!