Precedence of Logical Operators in C [duplicate]

2020-07-11 10:04发布

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

5条回答
看我几分像从前
2楼-- · 2020-07-11 10:35

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.

查看更多
老娘就宠你
3楼-- · 2020-07-11 10:39

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.

查看更多
爷的心禁止访问
4楼-- · 2020-07-11 10:52

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

if( !++a ) {
    ++b && ++c;
}
查看更多
甜甜的少女心
5楼-- · 2020-07-11 10:52

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

查看更多
劫难
6楼-- · 2020-07-11 10:54

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);
查看更多
登录 后发表回答