4.2.2 The switch statement that expresses the side-by-side condition selection: If ... If...... If......
In the real world, there is a special kind of conditional choice:
If it is sunny tomorrow, I will wear a T-shirt;
If it is cloudy tomorrow, I will wear a shirt;
If it is rainy tomorrow, I will wear a coat.
This is a conditional choice because it performs different actions according to different circumstances, and it is special because these different conditions (sunny, cloudy, rainy) belong to the same condition (weather conditions). As long as the condition is judged, we can use the IF statement to express it, using the If...else if ... described above. By the side-by-side conditional selection statement, we can express this view of the day's dressing as follows:
// Look at the clothes to be realized with the selection of parallel conditions
#include <iostream>
using namespace std;
// enumerate possible weather conditions
enum Weather
{
SUNNY = 1, // clear, specify its value as 1
CLOUDY, // cloudy, its value is incremented to 2
RAINY, // rainy day, its value is incremented to 3
};
int main ()
{
cout << "Please enter the weather tomorrow (1- sunny; 2- cloudy; 3- rainy):";
int nW = 0;
// Get user input weather conditions
cin >> nW;
// judge the weather
if (SUNNY == nW) // if it is sunny
{
// Output the clothes that should be worn on a sunny day
cout << "T-shirt on a sunny day" << endl;
}
else if (CLOUDY == nW) // if it is cloudy
{
cout << "wearing shirt on cloudy days" << endl;
}
else if (RAINY == nW) // if it is rainy
{
cout << "wearing a coat on a rainy day" << endl;
}
else
{
cout << "I don't know what the weather is tomorrow, what do you like to wear?" << endl;
}
return 0;
}
Using the side-by-side condition selection statement, although it is possible to express this side-by-side selection scenario, we have to write multiple if...else if ... Branching, to write multiple similar conditional expressions, seems a bit cumbersome. To simplify the code, and in order to make this side-by-side selection more explicit, C + + provides a specialized switch statement instead of a complex, parallel conditional selection statement with the following syntax:
switch (conditional)
{
case constant value 1:
{
Statement 1;
}
break;
case constant value 2:
{
Statement 2;
}
break;
// ...
case constant value n:
{
Statement n;
}
break;
default:
{
Default statement;
}
}
Where the condition is the condition to be judged, it can be a variable, such as the NW variable where we represent the weather condition, or it can be a more complex expression. and multiple constant values are the possible values for this condition, for example, the possible value of NW for our condition is sunny (Sunny), cloudly (Cloudy), or rainy (rainy day). At execution time, the switch statement calculates the value of the condition amount first, and then compares that value to the constant value of each case branch in order from top to bottom. If they are equal, they go into the corresponding case branch until they encounter the break keyword in the branch, ending the entire switch statement, and if they are not equal, continue to judge the following case branch. If a constant value equal to the condition is not encountered until the end, enter the default branch that represents the defaults to begin executing the complete switch statement at the end. The default branch represents the defaults for all exceptions that do not conform to the case branch condition, which is optional and omits the default branch if I do not need to handle exceptions. If there is no default branch and no matching case branch is found, the program ends the switch statement without executing any statements, as shown in 4-2.
Figure 4-2 the execution flow of the switch statement
With the switch statement, we can use it to replace the if...else if ... A side-by-side conditional selection statement simplifies the juxtaposition of "look-and-dress" to:
// Parallel conditional selection using switch statements
// Use nW representing the weather conditions as the condition quantity, and wear different clothes according to different weather
switch (nW)
{
case SUNNY: // Use SUNNY for sunny days as a constant value to process sunny conditions
cout << "T-shirt on a sunny day" << endl;
break; // Complete the processing of sunny conditions, use break to end the entire switch statement
case CLOUDY: // handle cloudy
cout << "wearing shirt on cloudy days" << endl;
break;
case RAINY: // handle rainy days
cout << "wearing a coat on a rainy day" << endl;
break;
default: // handle exceptions by default
cout << "I don't know what weather it is, what do you like to wear?"
}
Here, we use the variable NW, which represents the weather condition, as the conditional amount, and the enumeration values that identify the various weather conditions as constant values for each case branch. At execution time, the switch statement compares the conditional amount that holds the weather condition NW from the top down to the constant value of each case branch, which is equivalent to the "if (SUNNY = = NW)" In the parallel conditional selection statement. This equality comparison goes from top to bottom, until it encounters a branch that is equal, enters execution, and then encounters the break keyword to end the entire switch statement execution. In this way, the logical judgment of the switch statement implementation is preceded by the If...else if ... The side-by-side conditional selection statement is fully consistent, while the code is more concise, and various cases are listed separately with case branches, and the logic is clearer. Therefore, we should prefer to use the switch statement when expressing this condition selection for different conditions of the same condition.
The break keyword at the end of each case branch requires special attention when using the switch statement. Its function is to jump (break) out of the current case branch, ending the entire switch statement execution. In the example above, if the user input NW is 1, it means that tomorrow is sunny. Because the value of the SUNNY branch is equal to NW, the switch statement goes into the "case SUNNY" branch and outputs:
Wear T-shirts on sunny days
Then, when the break keyword is encountered, it ignores the other case branches and ends the execution of the entire switch statement. If there is no break keyword here, it will continue to execute the subsequent case branch down until the break keyword is encountered or all subsequent branches have finished executing. So, if the break keyword is missing from the switch statement, then the user enters 1 and the output is:
Wear T-shirts on sunny days
Wear a shirt on a cloudy day
Wear a coat on rainy days
I don't know what the weather is, what you wear, what you wear.
Look, the whole thing's messed up! Therefore, when using the switch statement, be sure to add the break keyword at the end of each case branch, indicating that the branch has finished processing and ending the entire switch statement execution.
Of course, nothing is absolute. Most of the time, we need to add the break keyword after each case branch, and in some special cases, where a common function needs to be done for multiple instances, one case branch function is part of another case branching function, and the two case branches have a relationship with the contained , it is also possible to intentionally remove the break keyword from the containing branch and place it in the upper position to achieve the common function code in the shared included branch. For example, when we order at KFC, we have a burger set and a chicken wing package to choose from. Burger package is just a burger, and the chicken wing package is made with a pair of chicken wings on the basis of the burger set. In this scenario, the two case branches (Hamburg package and chicken wing package) have a public function (a hamburger), and both form a relationship that contains and is included (the chicken wing package includes a burger package, while the burger package is included in the chicken wing package), in which case You can omit the break keyword containing the case branch (chicken Wing package) and place it in a relative position to achieve common public functionality:
cout << "Please select the package you need (1-burger course; 2-chicken wings course)" << endl;
int nOrder = 0;
cin >> nOrder; // Get user selection
switch (nOrder)
{
case 2: // put the containing case branch on top
cout << "A pair of chicken wings" << endl; // Complete unique functions
// Note that the break keyword at the end of the case branch is omitted here
case 1: // Place the included case branch lower
cout << "a burger" << endl; // complete public functions
break; // keep the break keyword and end the switch statement
default:
cout << "Unrecognized option, please reselect" << endl;
}
In this example, we intentionally omit the break keyword for the first case branch, and when we enter 1 to select the burger package, the switch statement goes into the "Case 1" branch, and after the output "one burger", it encounters the break keyword at the end, Thus ending execution of the entire switch statement. In the end, we get the content of the burger package:
A hamburger
And when we enter 2 to choose the chicken Wing package, the switch statement will first go to "Case 2" branch execution, output "a pair of chicken wings", because there is no break keyword, so it will continue down into the "Case 1" branch execution, output "a hamburger", It then encounters the break keyword, ending the entire switch statement execution. In the end, we get the contents of the Chicken Wing package:
A pair of chicken wings
A hamburger
Here, although we omit the break keyword at the end of some case branch, not only does it not cause a logical error, but it achieves the effect of common public function code.
There are several issues to note when using the switch statement:
(1) The conditional amount in parentheses after the Switch keyword must be a numeric variable or an expression of integral type, or another type that can be converted to an integral type, such as a character type or enumeration type.
(2) because the condition after switch is integer, the constant value after the case must also be an integral type in order to compare it. It is usually a number of enumeration values that represent a variety of situations, such as sunny, cloudly, etc. in the example above, or a constant number, such as the constant number 1 and 2, which represent options in the example above, or even constant expressions that only have constant participation in the operation.
(3) The constant values of each case branch cannot be equal, that is, there cannot be two of the same condition branch.
Hello, C + + (20) If it's sunny tomorrow, I'll wear a T-shirt; If it's cloudy tomorrow, I'll wear a shirt; if it rains tomorrow, I'll wear a coat. --4.2.2 The switch statement that expresses the side-by-side condition selection: If ... If...... If ...