Hello, Do C ++ (18) want to buy this watermelon? Priority between 4.1.6 operators and 4.1.6 Operators

Source: Internet
Author: User

Hello, Do C ++ (18) want to buy this watermelon? Priority between 4.1.6 operators and 4.1.6 Operators
4.1.6 priority between operators

When expressing complicated condition judgments, there may be multiple operators in the same expression. For example, when determining whether or not to buy a watermelon, we should not only determine its total price (unit price: 8.2 RMB/kg, total price: 10.3) whether it is less than 100 yuan (because there is only so much money in your pocket), and whether the watermelon is damaged or not. To express this complex condition judgment, we have to include all the Arithmetic Operators, Relational operators, and logical operators we have learned before:

Bool bBad = false; // determines whether there is a broken place float fPrice = 8.2; // The unit price float fWeight = 10.3; // weight // determine whether the total price is less than 100 and if (fPrice * fWeight <100 &&! BBad) {cout <"Buy watermelon" <endl ;}else {cout <"forget, don't buy" <endl ;}

In "fPrice * fWeight <100 &&! The bBad expression contains the arithmetic operator "*", the relational operator "<", and the logical operator "!". And "&". Which of the following operations should we start with in the same expression? What is the final result of this expression?

To understand the order in which an expression is calculated, you must first understand the computing priority between operators. Correct results can be obtained only when the calculation order is correct. In C ++, the priority of each operator is shown in Table 4-1.

Table 4-1 operator priority

Level

Operator

Description

1

()

Brackets are the leaders of all operators and have the highest priority. If there are brackets inside the brackets, the internal brackets have a higher priority.

2

! , + (Positive),-(negative), ++ ,--

They are all unary operators. They are usually calculated on the operands and continue to participate in the next calculation.

Note that the "+" and "-" here refer to the symbols that change the positive and negative attributes of values, rather than the symbols of addition and subtraction operations.

3

*,/, %

Multiplication, division, and remainder operations

4

+ ,-

Addition and subtraction

5

>,>=, <, <=, = ,! =

Relational operation

6

&&

Logic and Operation

7

|

Logic or operation

8

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

Assignment operation

The rule for calculating the order of expressions is: operators with higher priority are always calculated; operators with the same priority are calculated from left to right. After understanding the priorities of operators and the calculation rules of expressions, you can calculate the results of the above complex expressions. In this expression, the operator with the highest priority is the "!" operator that performs non-arithmetic operations on the bBad variable. Symbol, so it gives priority to the calculation to form the intermediate result:

FPrice * fWeight <100 & true // The value of bBad is false, and the result after non-calculation is true.

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

84.46 <100 & true // fPrice * the result of fWeight is 84.46

After the previous two steps, the entire expression is much clearer. Among the remaining two operators, the comparison-sized relational operator "<" has a higher priority and should be given priority. The intermediate result is:

true && true

Now, the only logic and operator "&" are left, and the final result is clear at a glance. The final result of the expression is true for the logic and operation of two true values. When a computer computes an expression, it calculates the expression in the order determined by the priority of each operator. This, in turn, requires us to design expressions in the same order of priority as the operator. Otherwise, the actual computing order is different from the one we imagined, and the calculated result is naturally quite different from what we imagined. In this sense, it is necessary to familiarize yourself with and master the priority of operators.

Best Practice: properly use parentheses to mark the order of expressions

From the above example, we can see that the computation of expressions that are too complex is very troublesome. Although expressions are calculated by computers, we don't have to worry about computer troubles. However, expressions are designed by programmers and must be provided to others for reading. Expressions that are too complex to be designed are prone to errors and the code is very readable. Therefore, we should try to avoid mixing multiple operators in the same expression, and try to keep the expression short and concise. When necessary, you can split a complex expression into multiple smaller expressions to calculate the intermediate results, and then combine the intermediate results to obtain the final results. For example, we can split the complex expression above into two smaller expressions to determine whether there are any bad parts and whether the total price is less than 100, then perform the "and" Operation on the two intermediate results to get the final result:

// Split the complex expression into two smaller expressions: bool bFresh =! BBad; // indicates whether fresh float fTotal = fPrice * fWeight; // calculates the total bool bMoney = fTotal <100; // determine whether the total price is less than 100 RMB // compare the intermediate results if (bFresh & bMoney )//...

After such splitting, the computation of each expression is clear, which reduces the possibility of errors and improves readability. But it also brings inconvenience, that is, the code is too cumbersome. To get the clear benefits of the split expression and avoid the inconvenience of code, you only need to use.

The priority of "()" is the highest among all operators. It can be used to artificially mark the computational order in the expression according to the intent of the designer. For example, you can rewrite the above expression and use parentheses to express the desired computing order, so that the meaning of the expression is clearer:

// …if(((fPrice * fWeight) < 100) && (!bBad))// …

After brackets are used, the order of calculation of the entire expression becomes clear: According to the calculation sequence determined by brackets, first calculate the bottom layer (fPrice * fWeight) to obtain the intermediate result 84.46, then calculate (84.46 <100) to get the intermediate result true, and then calculate (! BBad) to get the intermediate result true, and finally calculate "true & true" to get the final result true. After brackets are used, the calculation order is the same as the default order, but the code readability is increased, which makes the calculation order clear and avoids code being too cumbersome. In addition, in some special cases, when you need to change the default calculation order of an expression, parentheses are required.

In summary, after "()" is used, we want the expressions to be calculated in the order in which they are calculated. Mom no longer has to worry about the priority of each operator.

4.1.7 organize expressions into Idioms

Learning C ++ programming is actually how to use this special 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 chapter, we learned operators and various expressions composed of operators connected to operands. These expressions can only be called phrases in this language ", they can express some meaning, but they are incomplete:

// Phrase expression a // a separate variable. Nothing is done. // use the arithmetic operator "+" to calculate the sum of 3 and 2.

These expressions can be executed, but they do not change the state of the program, nor are the computing results retained, so there is no practical significance. Just as in English, we need to add the subject and the object to form a complete sentence. In C ++, we also need to combine some expressions that express scattered meanings, add a semicolon to end the statement to form a relatively independent and complete function. For example, by combining the above two expressions with the value assignment operator, a complete value assignment statement is formed:

// Value assignment statement a = 3 + 2;

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

In C ++, statements and expressions are not strictly distinguished. In many cases, a statement can be directly formed by adding a semicolon to an expression. The statement emphasizes the functions it completes, while the expression focuses on the calculation and final result it describes. Before that, we have come into contact with the two most common types of statements: variable definition statements and value assignment statements.

Know More: Statement blocks represented "{}"

When multiple consecutive statements belong to the same control structure, you can enclose these statements with a pair of braces "{}" to form a statement block, express a relatively independent meaning. In terms of usage, the statement block is not much different from a separate statement, but it means that it can Package Multiple statements into a statement block, this allows you to execute multiple statements in the for loop and other control structures. For example, in the for loop structure, we can calculate the sum of all integers from 1 to 100:

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

This statistic can be completed only by one statement. Naturally, this statement can be placed directly after the for loop structure. However, if we only need to count all the even sum in this interval, therefore, conditional judgment is required. This is not a separate statement. We must use "{}" to package all statements that determine the even number and count the even number into a statement block, and then place it in the for loop structure to complete the statistics:

For (int I = 1; I <= 100; ++ I) {// for Loop statement block start if (0 = I % 2) // judgment statement nTotal + = I; // Statistical Statement} // for Loop statement block end

In addition to the packaging statement, the statement block represents the starting position of the scope in C ++. For details about the scope, refer to the subsequent section 7.3.3.

Related Article

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.