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:

BOOLBbad =false;//If there's a place to break downfloatFprice =8.2;//Unit PricefloatFweight =10.3;//Weight//determine if the total price is less than 100 and whether it is brokenif(Fprice * Fweight < -&&!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 operations

7

||

Logical OR operation

8

=, + =, *=,/=,%=

Assignment operation

The evaluation order rule for expressions is that operators with higher precedence are always prioritized, and operators of the same precedence are evaluated in order from left to right. 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, the highest-priority operator is the logical non-operation of the Bbad variable "! "Symbol, so it takes precedence to get the operation to form such intermediate results:

 - true  // The value of Bbad is false, and the result after the non-operation is true

In this intermediate result expression, the highest priority is the multiplication arithmetic operator "*", which calculates the total price, and then computes it to get an intermediate result:

84.46  - true  // The result of Fprice*fweight is 84.46.

After the first two steps of calculation, the whole expression is much clearer. In the remaining two operators, the relative size of the relational operator "<" has a higher precedence and should be evaluated first, resulting in the intermediate result:

true 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

From the above example we can see that overly complex expressions are computationally cumbersome. 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:

// splitting a complex expression into two smaller expressions bool Bfresh =!bbad;    // indicates whether fresh float // Calculate Total Price BOOL ;  // determine whether the total price is less than 100 yuan // Compare  the 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:

// ... .. if ) && (!  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 expressions a        //  A single variable, nothing done 32    //  with arithmetic operator "+" Calculates the and of 3 and 2

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:

// Assignment Statements 3 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 0 ;  for (int1; + ++ = 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 (int1; + +// for Loop statement block start        if (0 = = i%2//  judgment Statement            //  Statistical             statement / / For Loop statement block end

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

Contact Us

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.