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
breakstatements at the end of the code for each branch are essential! If thebreakstatement is missing, the subsequent case code blocks will start execution until theswitchblock has finished execution or until anotherbreakstatement is encountered.
Rules
-
The value provided in each case can be integers or characters.
-
Duplicate cases are not allowed.
-
The
defaultcase is optional and will only be executed when none of the cases aretrue. -
The
breakstatement is not needed in thedefaultcase. -
It is possible to nest
switchstatements, 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