Reprint https://zhidao.baidu.com/question/426219427238900292.html
Question:
In this program, why not execute (++y)&&(++x) first? The program first judges x>y, and then the latter part of the expression is short-circuited. && is not higher priority than ||? How to explain.
Reply:
C/C++ has a short-circuit effect A || B in the logical judgment expression.
When A is logically true, the value of the entire expression can be determined to be true, and B does not execute
A && B. When A is logically false When the value of the entire expression can be determined to be false, B will not be executed.
Here x>y is true, so the following (++y)&&(++x) will not be executed.
Ask
当&&和||同时存在的时候,即 A || B && C 的时候,为什么不是先计算B&&C?
Follow up
如果A已经是逻辑真,就没必要再计算B&&C了。虽然&&的优先级比||高,用括号括起来看是这样:(A) || (B && C),
A和B&&C是同等优先运行的表达式,按照从左至右的运行规则,先计算A,发现A为逻辑真后,B&&C就不执行了。
优先级高只是结合(律)的问题(即括号怎么放的问题),但不是计算的先后顺序。