The arithmetic operations of addition, subtraction, multiplication and division are familiar ones. However, when several are used in an expression, some mechanism must be used to determine which operation is to be performed first, which one is second, and so on.
To illustrate, consider the expression:
Should we go left to right:16 + 8 / 4 - 1
Should we go right to left:((16 + 8) / 4) - 1 ⇒ (24 / 4) - 1 ⇒ 6 - 1 ⇒ 5
Should we start in the middle:16 + (8 / (4 - 1)) ⇒ 16 + (8 / 3) ⇒ 16 + 2 ⇒ 18
It obviously makes a difference which order we use.16 + (8 / 4) - 1 ⇒ 16 + 2 - 1 ⇒ 17
Modify your program to output the result of this expression without any parentheses. Compile and execute the program.
Question #3.6.1: Which of the orders listed above appears to be correct?
The order in which operators are applied is determined by a property known as operator precedence or priority. Each C++ operator is given a precedence or priority level, and operators with higher precedence are applied before those with lower precedence. In C++, the precedence of the operators we have seen thus far are as follows:
So, from this list, we can see that
/ should be applied
-. That's why we should start in the
16 + 8 / 4 - 1;
/. It's irrelevant that it's in the middle. Wherever the division appeared (with these operators), we'd always do it first.
As indicated at the top of the list, parentheses can be used to change the order in which operators are evaluated, with the operator in the inner-most parentheses being applied first. For example, in the expression
the subtraction is performed first, then the addition, and finally the multiplication.((9 - 1) * (1 + 1))
Compute, by hand, the value of the following expression:
1 / 2 * (3 - 4) * 5 + (6 % 7 - (8 - 9) / 8)
Question #3.6.2: What value did you get?
Then modify your source program to check your answer.
Question #3.6.3: What result did your program display?
Operator precedence is the reason why it is necessary to parenthesize a relational expression within an output statement. Consider the following code::
The output operator has higher precedence than the equality operator, so the value ofcout << i == j << endl;
iwould be inserted into
cout, then the equality operator would be applied to (essentially)
But an((cout << i) == j) << endl;
ostreamand an integer cannot be compared, so the compiler generates an error.
Question #3.6.4: What is the exact error message when you try to compile the parenthesis-free output statement?
If we instead parenthesize the expression explicitly as follows,
then the equality operator is applied first, producing a boolean value, and then the leftmost output operator is applied, inserting that boolean value intocout << (i == j) << endl;
cout. The rightmost output operator is then applied, inserting