C++ switch statement
Introduction
In this post, we will discuss the C++ switch statement and its flow in a simple C++ program. When a switch statement is executed, its expression is evaluated. If the value of the expression equals the case expression the flow is transferred to the action with the matching case expression.
Syntax
switch(SwitchExpression){
case CaseExpression1:
action1
break;
case CaseExpression2:
action2
break;
case CaseExpression3:
action3
break;
default:
defaultAction
}
Flowchart
C++ switch Statement
/************************* * C++ switch statement demo *************************/ #include <iostream> using namespace std; int main() { int operand1; int operand2; bool isValid=false; char mathOperator; int expResult; cout << "----Welcome to Simple Calculator-----" << endl; cout << "Please enter expression : " << endl; cout << "Example:" << endl; cout << "2" << endl; cout << "+" << endl; cout << "3" << endl; cout << "--------------------------------------" << endl; cin >> operand1; cin >> mathOperator; cin >> operand2; switch(mathOperator) { case '+': isValid=true; expResult = operand1 + operand2 ; break; case '-': isValid=true; expResult = operand1 - operand2 ; break; case '*': isValid=true; expResult = operand1 * operand2 ; break; case '/': isValid=true; if(operand2 != 0) expResult = operand1 / operand2 ; else cout << "Infinity!." << endl; break; default: isValid=false; cout << "Operator not supported" << endl; } if(isValid) { cout << "--------------------------------------" << endl; cout << "Result=" << endl; cout << operand1 << " " << mathOperator << " " << operand2 << " = " << expResult << endl; cout << "--------------------------------------" << endl; } return 0; }
Sample Run
—-Welcome to Simple Calculator—–
Please enter expression :
Example:
2
+
3
————————————–
1073
+
35451
————————————–
Result=
1073 + 35451 = 36524
————————————–
Process returned 0 (0x0) execution time : 11.207 s
Press any key to continue.
—
C++ Tutorials
C++ Tutorials on this website:
https://www.testingdocs.com/c-coding-tutorials/
For more information on the current ISO C++ standard
https://isocpp.org/std/the-standard