简体   繁体   English

关于 C 中运算符优先级的混淆

[英]Confusion about operator precedence in C

I got bit confused by how to interpret the precedence of operators in the following snippet:我对如何解释以下代码段中运算符的优先级感到有些困惑:

int a,b,c,d;
a=b=c=d=1;
a=++b>1 || ++c>1 && ++d>1

The values of a,b,c,d at the end of this code snippet are 1,2,1,1 respectively.此代码片段末尾的 a,b,c,d 的值分别为 1,2,1,1。 I was trying to decipher what was happening here but to no avail.我试图破译这里发生的事情,但无济于事。

I know the precedence of ++ is higher than any other operators so why b,c, and d doesn't equal 2?我知道 ++ 的优先级高于任何其他运算符,那么为什么 b、c 和 d 不等于 2? According to the result I received, I guess that the expression was evaluated left to right when at the first step b is incremented to 2 therefore ++b>1 is true then because there is a logical OR the answer is returned immediately.根据我收到的结果,我猜想当在第一步 b 递增到 2 时,表达式是从左到右计算的,因此 ++b>1 为真,因为有一个逻辑 OR 立即返回答案。 Like if it was : (++b>1) ||就像是: (++b>1) || (++c>1 && ++d>1) (++c>1 && ++d>1)

Does operator precedence have any other role other than to group operands together?除了将操作数组合在一起之外,运算符优先级还有其他作用吗? What does it have to do with the order of execution for example?例如,它与执行顺序有什么关系?

The reason is because of Short-circuit evaluation which means that the evaluation will stop as soon as one condition is evaluated true (counting from the left).原因是短路评估,这意味着只要一个条件被评估为true (从左数),评估就会停止。

This:这个:

a=++b>1 || ++c>1 && ++d>1

is therefore similar to this:因此类似于:

if(++b > 1) {
    a = true;
} else if(++c > 1) {
    if(++d > 1) {
        a = true;
    }
} 

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

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