英文:
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 <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);
}
I was expecting the value to be 1010 since I have read that && 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++ && 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,因为这是 || 运算符的结果,而 b 和 c 保持不变。
英文:
Operator precedence dictates how operands are grouped, not how they are evaluated.
Since && has higher precedence than ||, this:
d = a-- || b++ && c++;
Is the same as this:
d = (a--) || ((b++) && (c++));
Now looking at this, we can see that the left operand of || is a-- and the right operand is b++ && 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++ && 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论