What is a switch statement in C++?

What are switch statements?

switch (case) statements are a block of code that acts in the same manner as an if-else-if ladder.

The switch statement matches the variable value against every case statement and returns the value accordingly. If there’s no match, the default case executes.

The format is neater and easier to read than a block of multiple if-else statements.

Flowchart

Syntax

switch(var)
{
    case 1:
        // code for case 1
        break;
    case 2:
        // code for case 2
        break;
    default:
        // code for default
}

Note: The break statements at the end of the code for each branch are essential! If the break statement is missing, the subsequent case code blocks will start execution until the switch block has finished execution or until another break statement is encountered.

Rules

  1. The value provided in each case can be integers or characters.

  2. Duplicate cases are not allowed.

  3. The default case is optional and will only be executed when none of the cases are true.

  4. The break statement is not needed in the default case.

  5. It is possible to nest switch statements, but it is not recommended as it may reduce the readability of the code.

Code

Here is a code for a very simple calculator:

Please add a simple equation without white spaces as input, like: 4+2, 5-6, 3*3, 4/8, etc.

#include <iostream>
using namespace std;
int main() {
char op;
int first;
int second;
int ans = -1;
cout << "Please input first number: ";
cin >> first;
cout << first << endl;
cout << "Please input operator (+,-,*,/): ";
cin >> op;
cout << op << endl;
cout << "Please input second number: ";
cin >> second;
cout << second << endl;
cout << "Equation: " << first << " " << op << " " << second << endl;
switch(op)
{
case '+':
ans = first + second;
break;
case '-':
ans = first - second;
break;
case '*':
ans = first * second;
break;
case '/':
ans = first / second;
break;
default:
cout << "Incorrect Operator" << endl;
}
cout << "the answer is: " << ans;
return 0;
}

Enter the input below

Free Resources