开发者

Precedence of Logical Operators in C [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

why “++x || ++y && ++z” calculate “++x” firstly ? however,Operator “&&” is higher than &ldquo开发者_开发问答;||”

If you look at C's precedence table, you'll see that && has higher precedence than ||.

But take a look at the following code:

a=b=c=1;

++a || ++b && ++c;

printf("%d %d %d\n",a,b,c);

It prints out "2 1 1", meaning that the "++a" is evaluated first, and once the program sees a TRUE there it stops right there, because what is on the other side of the || is not important.

But since && has higher precedence than ||, shouldn't "++b && ++c" be evaluated first, and then the result plugged back into "++a || result" ? (in this case the program would print "1 2 2").


Just try to imagine it with parentheses:

++a || ++b && ++c;

equals

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

which is evaluated from left to right.

if && and || would have the same precedence, it would look like

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


The precedence rules only say that it will be evaluated like this:

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

Now comes the short circuiting behavior of the logic operators which says that you have to evaluate terms from left to right and stop when the result is known. The part on the right never gets executed.


Precedence and order of evaluation are two completely different things. For logical operator expressions, evaluation is always left-to-right. The expression ++a || ++b && ++c is interpreted as

  1. Evaluate ++a
  2. If the result of 1 is zero, evaluate ++b && ++c

The expression is parsed as ++a || (++b && ++c); the whole expression is true if either of the subexpressions ++a or ++b && ++c is true.


&& has higher precedence only in parse tree. But compiler optimizes the code as

if( !++a ) {
    ++b && ++c;
}


Your example ++a || ++b && ++c is the same as ++a || (++b && ++c).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜