Short circuit evaluation of a statement with ++ operator in C

我怕爱的太早我们不能终老 提交于 2019-12-01 02:35:09

You are confused about precedence and order of evaluation.

Precedence defines how the operators are grouped, i.e

c = a++ && b++;

is equivalent to:

c = ((a++) && (b++));

Order of evaluation defines how the expression is evaluated, the short circuit of && means a++ is evaluated first, if it's zero, the end; if it's not zero, b++ is then evaluated.


As another example:

c = (a++) + (b++);

Is a++ evaluated before b++? The answer is we don't know. Most operators don't define the order of evaluation. && is one of the few operators that do define. (The rest are ||, , and ?:)

There are two concepts here - order of precedence and order of evaluation. Order of precedence will have an impact only if an expression (or sub-expression) is evaluated.

In general, the order of evaluation is not sequenced. Given an operator, its operands can be evaluated in any order. The arguments of a function can be evaluated in any order.

From the C++ Standard:

1.9 Program execution

15 Except where noted, evaluations of operands of individual operators and of subexpressions of individual expressions are unsequenced.

and

8.3.6 Default arguments

9 Default arguments are evaluated each time the function is called. The order of evaluation of function arguments is unspecified.

For the logical AND operator, &&, the C++11 standard says:

5.14 Logical AND operator

1 The && operator groups left-to-right. The operands are both contextually converted to type bool (Clause 4). The result is true if both operands are true and false otherwise. Unlike &, && guarantees left-to-right evaluation: the second operand is not evaluated if the first operand is false.

Similar exception is specified for the logical OR operator, ||.

Since b++ is not evaluated due to short circuiting of the expression because of && operator, the order of precedence of the operators has no significance in this particular case.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!