用C逻辑运算符precedence [英] Precedence of Logical Operators in C
问题描述
可能重复:结果
<一href=\"http://stackoverflow.com/questions/3700352/why-x-y-z-calculate-x-firstly-however-operator-is-higher\">why &ldquo; ++点¯x|| ++ Y'放大器;&安培; ++ž&rdquo;的计算&ldquo; + X'rdquo;的首先 ?然而,运营商及ldquo;&放大器;&安培;&rdquo;的比&ldquo更高; ||&rdquo;的
如果你看看C'S precedence表,你会看到和放大器;&安培;具有较高的precedence比||。
If you look at C's precedence table, you'll see that && has higher precedence than ||.
不过看看下面的code:
But take a look at the following code:
a=b=c=1;
++a || ++b && ++c;
printf("%d %d %d\n",a,b,c);
据打印出2 1 1,这意味着++一个先评估,一旦程序看到一个真正有它就停在那里,因为什么是对的另一边||并不重要。
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.
但是,由于&功放;&安培;具有较高的precedence比||,不应该++ B和;&功放; + C先评估,然后将结果插回++一个||结果? (在这种情况下,程序将打印1 2 2)。
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;
等于
(++a) || (++b && ++c);
这是从左至右评价
which is evaluated from left to right.
如果&功放;&安培;和||将具有相同的precedence,它看起来像
if && and || would have the same precedence, it would look like
(++a || ++b) && (++c);
这篇关于用C逻辑运算符precedence的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!