Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Impara Switch Statement | Conditional Statements
Introduction to C++

book
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:

python
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:

int weekendDay = 1;
switch (weekendDay) {
    case 1:
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;cout << "It's Saturday";
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;break;
&nbsp;&nbsp;&nbsp;&nbsp;case 2:
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;cout << "It's Sunday";
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;break;
}
123456789
int weekendDay = 1; switch (weekendDay) { &nbsp;&nbsp;&nbsp;&nbsp;case 1: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;cout << "It's Saturday"; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;break; &nbsp;&nbsp;&nbsp;&nbsp;case 2: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;cout << "It's Sunday"; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;break; }
copy

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.

question-icon

Let’s write a calculator which accepts the variable a and b type of double, sign type of char, and makes calculations.

// Declare variables
double a, b;
char sign;

// User input
cin >> a;
cin >> b;
cin >> sign;

// Write calculator
_ _ _
{
    case '-':
        cout << a - b;
        break;
    case '+':
        cout << a + b;
        
_ _ _
;
    case '*':
        
_ _ _
a * b;
        break;
    
_ _ _
:
        cout <<
_ _ _
;
        break;
}

Click or drag`n`drop items and fill in the blanks

dots
if (sign)
dots
a % b
dots
break
dots
a / b
dots
switch (sign)
dots
cout >>
dots
case '/'
dots
case '%'
dots
cout <<

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 3. Capitolo 8
some-alt