# Hello, C + + (18) Do you want to buy this watermelon? Order of precedence between 4.1.6 operators

Source: Internet
Author: User

Order of precedence between 4.1.6 operators

In the expression of some more complex conditional judgments, in the same expression, sometimes there may be multiple operators. For example, we judge whether to buy a watermelon, not only to determine its total price (8.2 yuan/catty, altogether 10.3 kilograms) is less than 100 yuan (because there is only so much money in the pocket), but also to determine whether the watermelon has a bad place. To express this complex conditional judgment, we have to put all the arithmetic operators, relational operators and logical operators we have learned before:

```bool bBad = false; // Is there anything broken?
float fPrice = 8.2; // unit price
float fWeight = 10.3; // weight
// determine if the total price is less than 100 and broken
if (fPrice * fWeight <100 &&! bBad)
{
cout << "Buy watermelon" << endl;
}
else
{
cout << "Forget it, don't buy it" << endl;
} ```

In the expression "Fprice * Fweight < &&!bbad", there is an arithmetic operator "*", a relational operator "<", and a logical operator "!" and "&&". So, so many operators in the same expression, in the end, which operation should start? What is the final result of this expression?

To figure out what order an expression is calculated in, you have to figure out the priority of the calculation between the operators. The correct results can be obtained by calculating the correct calculation order. In C + +, the precedence of each operator is shown in table 4-1.

Table 4-1 Precedence of operators

 Level operator Description 1 ( ) Parentheses are the leaders in all operators, with the highest precedence. If there are parentheses inside the parentheses, the inner brackets are more high-priority 2 ！ , + (plus),-(minus sign), + + 、-- All of them are unary operators, which are often the result of calculation of operands and continue to participate in the next calculation Note that the +,-refers to the symbol that changes the positive and negative properties of the value, not the plus or minus operation. 3 *、/、% Multiply, divide, take remainder operations 4 +,- Add and subtract operations 5 >, >=, <, <=, = =,! = Relational operations 6 && Logic and operation, which evaluates the value of its left expression first, and then continues to evaluate the value of the right-hand expression when its value is true, and finally calculates the logic of the two value 7 || Logical OR operation, it will also first calculate the value of its left expression, if its value is false, continue to calculate the value of the right expression, and finally calculate the logic of two values or 8 =, + =, *=,/=,%= Assignment operation

The evaluation order rules for expressions are: operators with higher precedence are always prioritized, operators of the same precedence are evaluated in left-to-right order, and if there are special rule operators (such as Logic and "&&"), the calculations are made according to special rules. After the precedence of the operators and the calculation rules of the expressions are clear, the result of the above complex expression can be computed. In this expression, there is an operator "&&" with a special rule, and according to its calculation rule, the expression evaluates to the value of its left expression first:

```  The left-hand expression of the first calculation
```

In this expression, there is no special rule operator, which is calculated according to the precedence of the operator. The highest priority is the multiplication arithmetic operator "*" that calculates the total price, which is calculated to get an intermediate result:

```  The result of fprice*fweight//is 84.46
```

This intermediate result expression has only one operator, and the result value is calculated directly to true. According to the calculation rule of the "&&" operator, if the value of the left expression is true, the value of its right expression continues to be evaluated. So, the next expression to be evaluated becomes:

```True &&!bbad // left-hand expression evaluates to intermediate result after completion
```

On the right side of "&&" there is only one operator "!", and the resulting intermediate result is:

```True
```

Now, the only logical AND operator "&&" is left, and the final result is at a glance, and the final result of the expression is true for the logic and operation of the two true values. When a computer evaluates an expression, it is calculated in the order in which it is prioritized by the individual operators. This, in turn, requires that when designing expressions, we must also follow the precedence of operators in order to design expressions. Otherwise, the actual order of calculation is different from the order of calculation we envision, and the resulting calculation will naturally differ from our assumptions. In this sense, it is necessary to be familiar with and master the precedence of operators.

Best practice: Use parentheses to indicate the order in which expressions are evaluated

As we can see from the above example, overly complex expressions are very cumbersome to calculate. Although the expression is computed by the computer, we don't have to worry about the computer for fear of trouble. However, the expression is designed by programmers and is also provided to others for reading. Designing overly complex expressions is error-prone, and the code is very readable. So we should try to avoid mixing multiple operators in the same expression, and try to keep the expression short and concise. When necessary, the complex expression can be split into smaller expressions to calculate the intermediate results, and then combine the intermediate results to get the final result. For example, we can split the complex expression above into two smaller expressions, determine if there is a bad place and whether the total price is less than 100, and then the two intermediate results are "and" to get the final result:

```// split complex expression into two smaller expressions
bool bFresh =! bBad; // indicates whether it is fresh
float fTotal = fPrice * fWeight; // calculate the total price
bool bMoney = fTotal <100; // determine if the total price is less than 100 blocks
// compare intermediate results
if (bFresh && bMoney)
// ...
```

With this split, each expression is calculated with clarity, reducing the likelihood of errors and improving readability. But it also brings a disadvantage, which is that the code becomes too cumbersome. You can only use "()" If you want the clear benefits of splitting an expression, but also to avoid the cumbersome inconvenience of code.

The priority of "()" is the highest of all operators, and it is possible to artificially label the order of calculation in an expression according to the designer's intent. For example, you can rewrite the expression above, use parentheses to express the order of the calculations we want, and make the meaning of the expression clearer:

```..... ) && (!  Bbad))// ...
```

With parentheses, the Order of evaluation for the entire expression becomes clear: in the order of calculation determined by the parentheses, the innermost (Fprice * fweight) is computed first to get the intermediate result 84.46, and then the calculation (84.46 < 100) to get the intermediate result true, and then calculate (!bbad ) Gets the intermediate result of true, and finally evaluates "True && true" to get the final result true. After using parentheses, the order of calculation is the same as the default order, but it increases the readability of the code, allowing us to get a clear understanding of the order of calculations and avoid making the code too cumbersome. In addition, parentheses become a must when you need to change the default calculation order of an expression in some special cases.

To sum up, after using "()", we want to let the expression in what order to calculate in what order, Mom no longer worry about I can't remember the priority of the operators.

4.1.7 to organize expressions into statements

Learning C + + programming, in fact, is learning how to use this particular language to describe and express the real world, just as we learn English to use it to describe and express the real world. In the previous chapters, we learned about operators and learned the various expressions that are made up of operator-connected operands, which can only be regarded as "phrases" in this language, and they may express certain meanings, but they are incomplete:

```phrase expression a // A single variable, do nothing // with arithmetic operator "+" to calculate 3 and 2 and
```

These expressions can be executed, but they do not change the state of the program, nor are the results preserved, so there is no practical meaning. Just like in English we need to add the main predicate to the phrase to form a complete sentence, in C + +, we also need to combine some expressions of scattered meaning, and finally add an English semicolon to end, so as to form a statement to complete a relatively independent and complete function. For example, by combining the above two expressions with an assignment operator, a complete assignment statement is formed:

```  2;
```

After the statement is formed, it expresses a complete meaning: computes the sum of 3 and 2 with the arithmetic operator "+" and assigns it to the variable A.

In C + +, statements and expressions do not have a strict distinction. Many times, an expression with a semicolon can directly form a statement. The statement emphasizes the functionality it accomplishes, while the expression focuses on the operations it describes and the final result. Prior to this, we have been exposed to two of the most common types of statements: variable definition statements and assignment statements.

Know MORE: block of statements using "{}"

When successive multiple statements belong to the same control structure, these statements can be enclosed in a pair of curly braces "{}" to form a block of statements that collectively express a relatively independent meaning. In use, a statement block is not much different from a single statement, but its meaning is that it can package multiple statements into a single statement block, allowing multiple statements to be executed in a control structure such as a For loop. For example, in a for loop structure, we can do this to count all integers from 1 to 100 and:

```

int nTotal = 0;

for(int i = 1; i <= 100; ++i)
nTotal += i;

```

This statistic can be done with just one statement, which can be done directly after the for loop structure, but if we only need to count all the even numbers in this interval, then we need to add the conditional judgment, which is not a single statement to complete. We must use "{}" to package all the statements that determine even numbers, the even number of statistics, into a block of statements, and then put them in the for loop structure before we can complete the statistics:

```for (int i = 1; i <= 100; ++ i)
{// start of for loop block
if (0 == i% 2) // judgment statement
nTotal + = i; // statistical statement
} // end of for loop statement block
```

In addition to packing statements, another meaning of a statement block is that it represents the commencement location of a scope in C + +. Refer to the subsequent 7.3.3 section for a specific description of the scope.

Hello, C + + (18) Do you want to buy this watermelon? Order of precedence between 4.1.6 operators

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.