use of && and | operators together in a expression

吃可爱长大的小学妹 提交于 2019-12-11 02:09:36

问题


cond && cond op cond

op can be && or ||

Qn- For short circuit (&&) operator if the first cond is false then right part (whole) is not evaluated or just the second cond after && is not evaluated

Also why the result of following two expressions different?

(2 > 3 && 5 < 2 || 3 > 2) => True

(2 > 3 && 5 < 2 | 3 > 2) => False

Can't we use short circuit operator and standard operators in a single expression...?


回答1:


The results are different because | and || have different precedence.

Specifically, | has higher precedence than &&, whereas || has lower precedence than &&.

          System.out.println(2 > 3 && 5 < 2 || 3 > 2);    // true
          System.out.println(2 > 3 && 5 < 2 | 3 > 2);     // false
          System.out.println(2 > 3 && (5 < 2 | 3 > 2));   // false
          System.out.println((2 > 3 && 5 < 2) | (3 > 2)); // true



回答2:


Your results differ because your second case uses | instead of ||. | is the bit-wise or, which is different from the logical or.

Now you say short-circuit expressions vs. standard expressions, but in many languages short-circuit expressions are the default (or only way) logical expressions are evaluated.

If by "standard" you mean bit-wise operators like & or |, then you can mix and match them with logical operators, although the results may not be what you expect.



来源:https://stackoverflow.com/questions/13827498/use-of-and-operators-together-in-a-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!