Logical Operations not as expected in C.

huangapple go评论46阅读模式
英文:

Logical Operations not as expected in C

问题

#include <stdio.h>;

void main() {
int a = 2, b = -1, c = 0, d;
d = a-- || b++ && c++;
printf("%d%d%d%d", a, b, c, d);
}

我期望的值是 1010,因为我读过 && 的优先级高于 ||,所以应该首先进行评估。但答案似乎是 1-101。有人可以解释为什么吗?我知道短路评估规则,但不明白为什么 b++ && c++ 不是首先执行的?

英文:

Can someone explain how the following code functions

#include &lt;stdio.h&gt;

void main() {
    int a = 2, b = -1, c = 0, d;
    d = a-- || b++ &amp;&amp; c++;
    printf(&quot;%d%d%d%d&quot;, a, b, c, d);
}

I was expecting the value to be 1010 since I have read that &amp;&amp; has more priority than ||, hence it should be evaluated first. But the answer seems to be 1-101. Could someone explain why? I know about the short circuit evaluation rule, but just don't understand why b++ &amp;&amp; c++ isn't performed first?

答案1

得分: 6

运算符优先级规定了操作数的分组方式,而不是它们的求值顺序。

由于 && 的优先级高于 ||,因此这个表达式:

d = a-- || b++ && c++;

等同于:

d = (a--) || ((b++) && (c++));

现在看看这个表达式,我们可以看到 || 的左操作数是 a--,右操作数是 b++ && c++。所以首先评估 a--,由于 a 的值是2,因此这个表达式的值为2。这使得 || 的左侧为真,意味着右侧,即 b++ && c++,不会被求值。因此,由于 || 的左操作数非零,|| 运算符的结果为1。

所以 a 减少到1,d 被赋值为1,因为这是 || 运算符的结果,而 bc 保持不变。

英文:

Operator precedence dictates how operands are grouped, not how they are evaluated.

Since &amp;&amp; has higher precedence than ||, this:

d = a-- || b++ &amp;&amp; c++;

Is the same as this:

d = (a--) || ((b++) &amp;&amp; (c++));

Now looking at this, we can see that the left operand of || is a-- and the right operand is b++ &amp;&amp; c++. So a-- is evaluated first, and since the value of a is 2 this expression evaluates to 2. This makes the left side of || true, meaning that the right side, i.e. b++ &amp;&amp; c++, is not evaluated. So because the left operand of || is nonzero, the result of the || operator 1.

So a is decremented to 1, d is assigned 1 because since that is the result of the || operator, and b and c are unchanged.

huangapple
  • 本文由 发表于 2023年6月12日 22:40:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/76457742.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定