Expression in C++

There are three things we should take into account. Priority, Accosiation and Evaluation Order.

Priority

According priorities of operators, all operators are divided into serval groups in which operators have the same priority. Operator with higher priority is prior to lower operator. Thus, elements around higher priority operator will be associated together. For example: expression

a = b + c * d - e;

is equvilent to the expression

a = b + (c * d) - e;

because priority of multiply operator (*) is higher than that of plus and minus operator (+-).

Association

In case of one element has two operators on the left hand and on the right hand each, what should compiler do? The answer is association. Take last case as an example. Because compiler take c * d as a whole, we can use t to denote this part instead. Rewrite the expression as following:

a = b + t - e;

Here is the case: plus and minus operators have the same priority. To solve this problem that how to compute this expression, we should take association into consideration. What the association do is to stipulate compute direction, such as from left to the right or from the opposite direction. The association of plus and minus operator is left-to-right association, so b + t should be computed first (use r to denote the result of b + t) and then compute r - e.

Evaluation Order

C++ does not define evaluation order, so the following expression is undefined

a = f() * g() /  g();

if a global variable is modified in g().

But there are four operators whose evaluation order is defined, they are logical and, (&&) logical or (||) , condition (?:) and comma (,) operator.

  • expression 1 && expression 2 association: left-to-right, evaluation order: evaluate expression 2 only in case expression 1 is TRUE.
  • expression 1 || expression 2 association: left-to-right, evaluation order: evaluate expression 2 only in case expression 1 is FALSE.
  • condition ? expression 1 : expression 2 association: right-to-left, evaluation order: evaluate condition first, if condition is true, then evaluate expression 1, otherwise, evaluate expression 2.
  • expression 1 , expression 2 association: left-to-right, evaluation order: evaluate expression 1 first and then evaluate expression 2.

 

HERE I WILL USE AN EXAMPLE TO EXPLAIN ASSOCIATION AND EVALUATION ORDER.

(a == b) ? c : d == e ? f : g

In this expression, here are only one kind of operator ?:. They have the same priority of course. Then, use association which is right-left in this case to get compute direction

(a == b) ? c : (d == e ? f : g)

Then use evaluation order to compute this expression.

First, evaluate condition expression.If TRUE, evaluate c and return. Otherwise, evaluate (d == e ? f : g). To get result of (d == e ? f : g), condition expression should be evaluated first. If TRUE, evaluate f and return, otherwise evaluate g and return.

发表评论

电子邮件地址不会被公开。 必填项已用*标注

5 × 4 =

− 1 = 1