Precedence of Logical Operators in C [duplicate]

2020-07-11 10:01发布

问题:

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

Possible Duplicate:
why “++x || ++y && ++z” calculate “++x” firstly ? however,Operator “&&” is higher than “||”

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").

回答1:

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);


回答2:

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.



回答3:

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.



回答4:

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

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


回答5:

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