# Hello, C ++ (20). 4.2.2 represents the switch statement selected by the parallel condition: if ...... If ...... If ......,. 4.2.2

Source: Internet
Author: User

Hello, C ++ (20). 4.2.2 represents the switch statement selected by the parallel condition: if ...... If ...... If ......,. 4.2.2
4.2.2 expression of the switch statement selected by the parallel condition: if ...... If ...... If ......

In the real world, there are also such special conditions:

If tomorrow is Sunny, I will wear a T-shirt;

If tomorrow is cloudy, 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 based on different situations. The reason for this is that it is special because of these different situations (Sunny, cloudy, and rainy) belong to the same condition (weather condition ). As long as it is a conditional judgment, we can use the if statement to express it, using the if... Else if... The parallel condition selection statement can express the daily dressing scenario 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;
}
```

Although this parallel selection scenario can be expressed using the parallel condition selection statement, we have to write multiple if... Else if... Branch. It is complicated to write multiple similar conditional expressions. To simplify the code and make the parallel Condition Selection clearer, C ++ provides a dedicated switch statement to replace the complex parallel condition selection statement. The syntax format is as follows:

```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;
}
}
```

The condition quantity is the condition to be judged. It can be a variable. For example, here we represent the nW variable of the weather condition, or a more complex expression. Multiple constant values are possible values of this condition. For example, the possible value of the condition value nW here is SUNNY, CLOUDLY, or RAINY ). During execution, the switch statement first calculates the value of the condition quantity, and then compares the value with the constant values of each case Branch in order from top to bottom. If the two are equal, execute the corresponding case branch until the break keyword in the branch is met to end the execution of the entire switch statement. If the two are not equal, continue to judge the next case Branch. If no constant value equal to the condition quantity is encountered until the end, the default branch indicating the default condition is entered and the entire switch statement is finally executed. The default branch is used by default to handle all exceptions that do not meet the case branch condition. It is optional. If you do not need to handle exceptions, You can omit the default branch. If no default branch exists and no matching case Branch is found, the program ends the switch statement without executing any statements, as shown in Figure 4-2.

Figure 4-2 execution process of the switch statement

With the switch statement, we can use it to replace if... Else if... Statement to simplify the parallel Condition Selection of "day clothes":

```// 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?" << endl;
}
```

Here, we use the variable nW that represents the weather condition as the condition quantity, and the enumerated value that identifies the weather condition as the constant value of each case Branch. During execution, the switch statement will compare the weather condition nW with the constant values of each case branch from top to bottom, it is equivalent to the condition judgment such as "if (SUNNY = nW)" in the parallel condition selection statement. The equal comparison proceeds from top to bottom until the branches of the two are equal. Then, the entire switch statement is executed when the break keyword is met. In this way, the logic judgment implemented by the switch statement is compared with that implemented by the if... Else if... The parallel condition selection statement is fully consistent, but the code is more concise. In various cases, the case Branch is used for separate listing, and the logic is clearer. Therefore, when expressing this selection of conditions for different conditions of the same condition, we should give priority to the switch statement.

Note the break keyword at the end of each case branch when using the switch statement. It is used to exit the current case Branch and end the execution of the entire switch statement. In the preceding example, if the input nW is 1, it indicates that tomorrow is sunny. Because the value of the SUNNY branch is equal to that of the nW branch, the switch statement is executed in the "case SUNNY" Branch and the output is as follows:

T-shirt on Sunday

When the break keyword is met, the execution of the entire switch statement is directly ended by ignoring other case branches. If there is no break keyword, it will continue to execute the subsequent case branch until the execution of the break keyword or all subsequent branches is completed. Therefore, if the break keyword is missing in the switch statement, the user enters 1 and the output is:

T-shirt on Sunday

Wear a shirt on a cloudy day

Coat on rainy days

I don't know what the weather is. What do you like to wear?

Look, it's a mess! Therefore, when using the switch statement, you must add the break keyword at the end of each case Branch, indicating that the branch is processed completely and the entire switch statement is executed.

Of course, there is no absolute thing. Most of the time, we need to add the break keyword after each case Branch. In some special cases, that is, when multiple case branches have a common function to complete, A case branch function is part of another case branch function. The two case branches have a relationship with the included branch. In this case, you can intentionally remove the break keyword in the branch, and place it on the top to share the code that is included in the branch to implement common functions. For example, we have a hamburger package and a chicken wings package to choose from when ordering at KFC. The hamburger package is just a hamburger, and the chicken wings package is based on the hamburger package plus a pair of chicken wings. In this scenario, two case branches (hamburger package and chicken wings package) have public functions (one hamburger ), in addition, the two forms the relationship between inclusion and inclusion (the chicken wings package includes the hamburger package, and the hamburger package is included in the chicken wings Package). In this case, you can omit the break keyword that contains the case Branch (Chicken Wings package) and place it in a relatively low position to achieve shared public functions:

```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 of the first case Branch. When we input 1 to select the hamburger package, the switch statement will go to the "case 1" branch for execution. After "one hamburger" is output, the break keyword at the end is met to end the execution of the entire switch statement. In the end, we get the following hamburger package:

A hamburger

When we enter 2 to select the chicken wings package, the switch statement will first go to the "case 2" branch for execution and output "a pair of chicken wings", because there is no break keyword here, therefore, it will continue to go down to the "case 1" branch and output "a hamburger". Then it will encounter the break keyword to end the entire switch statement execution. In the end, we get the following chicken wings package:

A pair of chicken wings

A hamburger

Although the break keyword at the end of some case branches is omitted here, it not only does not cause logical errors, but achieves the effect of sharing common function code.

When using the switch statement, pay attention to the following issues:

(1) The condition quantity in the brackets after the switch keyword must be a numerical variable or expression of an integer, or other types that can be converted to an integer, such as the character type or enumeration type.

(2) because the conditional quantity after the switch is an integer, to compare it with it, the constant value after the case must also be an integer. It is usually an enumeration value that represents various situations, such as SUNNY and CLOUDLY in the preceding example. It can also be a constant number, for example, the constant numbers 1 and 2 in the preceding example, it can even be a constant expression where only constants are involved in the operation.

(3) The constant values of each case branch cannot be equal, that is, two case branches with the same condition cannot appear.

Related Keywords:
Related Article

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

## A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

• #### Sales Support

1 on 1 presale consultation

• #### After-Sales Support

24/7 Technical Support 6 Free Tickets per Quarter Faster Response

• Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.