简体   繁体   English

C中“或”和“与”运算符的优先级

[英]Precedence of 'or' and 'and' operators in C

In the following code, I am getting 10 | 在下面的代码中,我得到10 | 1 | 1 | 1 as a result. 结果为1。 But according to precedence rules shouldn't 'and' operator must be evaluated first?(and yield c=9) Like : d = a || 但是根据优先级规则,不应该首先对'and'运算符进行求值吗(并得出c = 9),例如:d = a || (--b)&&(--c) since 'and' has higher precedence. (--b)&&(-c),因为“和”具有更高的优先级。 ( or shortcutting breaks precedence rules ?)Thanks in advance. (或快捷键会中断优先级规则?)预先感谢。

#include <stdio.h>
#include <stdlib.h>

int main(){
    int a,b,c,d;
    a =1;
    b = c = 10;
    d = a|| --b&&--c;
    printf("%d\n",c);
    printf("%d\n",a);
    printf("%d\n",d);
    return 0;
}

Precedence and order of evaluation are two different things. 评估的优先级和顺序是两个不同的事物。 From Logical OR documentation (emphasis mine): 逻辑或文档(重点是我的):

There is a sequence point after the evaluation of lhs. 评估lhs之后有一个序列点 If the result of lhs compares unequal to zero, then rhs is not evaluated at all (so-called short-circuit evaluation). 如果lhs的结果不等于零,则根本不评估rhs(所谓的短路评估)。

In case of exp1 || exp2 如果是exp1 || exp2 exp1 || exp2 , exp1 is always evaluated first as there is a sequence point after it and if exp1 is non-zero then exp2 is not evaluated. exp1 || exp2exp1总是首先被评估,因为它后面有一个序列点;如果exp1不为零,则不评估exp2

Precedence only determines which operands are grouped with which operators - it does not control the order in which expressions are evaluated. 优先级仅确定将哪些操作数与哪些运算符组合在一起-它不控制表达式的求值顺序。

In your example, it means the expression is parsed as 在您的示例中,这意味着表达式被解析为

a || (––b && ––c)

Both || 两者|| and && force left-to-right evaluation 1 . &&强制从左到右评估1 Both introduce a sequence point (IOW, the left hand operand will be evaluated and all side effects will be applied before the right hand operand is evaluated). 两者都引入了序列点(IOW,将评估左操作数,并且在评估右操作数之前将应用所有副作用)。

Both operators short-circuit - if the left operand of || 两个运算符都短路 -如果||的左操作数 evaluates to non-zero, then the result of the expression is 1 (true) regardless of the value of the right operand, so the right operand isn't evaluated at all. 计算结果为非零,则表达式的结果为1(true),而不管右操作数的值如何,因此完全不计算右操作数。 If the left operand of && is 0, then the result of the expression is 0 (false) regardless of the value of the right operand, so the right operand isn't evaluated at all. 如果&&的左操作数为0,则表达式的结果为0(false),而与右操作数的值无关,因此完全不评估右操作数。

In your expression, a is evaluated first. 在您的表达式中,首先评估a It has a non-zero value (1), so ––b && ––c is not evaluated. 它具有非零值(1),因此不评估––b && ––c


  1. Along with the ?: and comma operators. 连同?:和逗号运算符。 All other operators (arithmetic, equality, subscript, etc.) do not force a particular order of evaluation. 所有其他运算符(算术,等式,下标等)均不强制执行特定的评估顺序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM