English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this article, you will learn about the switch statement in C ++programming (with an example).
C++ switch statementto execute a statement from multiple conditions. It is similar to creating a switch statement in C++inif-else-if
.
But the switch statement is usually faster than if ... else. Additionally, the syntax of the switch statement is more concise and easier to understand.
switch (n) { case constant1: //If n is equal to constant1, the following code will be executed; break; case constant2: //If n is equal to constant2, the following code will be executed; break; . . . default: // If n does not match any constant, the following code will be executed }
when a constant1, constant2....constant) when the program control is passed to the code block associated with the case.
In the above code, the assumed value n is equal to constant2. The compiler will execute the constant2block of code until the end of the switch block or encounteringbreak statement.
The break statement is used to prevent the code from entering the next case.
The diagram above shows how the switch statement works and checks the condition in the switch case clauses.
// The program uses a switch statement to build a simple calculator #include <iostream> using namespace std; int main() { char o; float num1, num2; cout << "Enter an operator (+, -, *, /): "; cin >> o; cout << "Enter two operands: "; cin >> num1 >> num2; switch (o) { case '+: cout << num1 << " + << num2 << " = " << num1+num2; break; case '-: cout << num1 << " - << num2 << " = " << num1-num2; break; case '*: cout << num1 << " * << num2 << " = " << num1*num2; break; case '/: cout << num1 << " / << num2 << " = " << num1/num2; break; default: // The operator does not match any of the following (+, -, *, /) cout << "Error! Operator is incorrect"; break; } return 0; }
Output the result
Input an operator (+, -, *, /) + - Input two operands: 2.3 4.5 2.3 - 4.5 = -2.2
input by the user - the operator is stored in the variable o. And the two operands2.3and4.5are stored in the variable num1and num2in.
Then, the program control jumps to
cout << num1 << " - << num2 << " = " << num1-num2;
Finally, the break; statement ends the switch statement.
If the break statement is not used, all the case statements after the matching case will be executed.