简体   繁体   English

哪个布尔表达式首先在包含OR操作的IF语句中求值?

[英]Which boolean expression gets evaluated first in an IF statement containing an OR operation?

In the following statement, in VC++, which boolean expression gets evaluated first? 在以下语句中,在VC ++中,哪个布尔表达式首先被求值? Also, do they both get evaluated? 另外,他们俩都得到评估了吗?

if( (X==Y) || (Z==T))
{
 //code here
}

从左到右评估它们,如果第一个为真,则表达式短路,而第二个不评估。

If the built-in || 如果内置|| operator is used, then X == Y will be evaluated before Z == T is evaluated. 使用运算符,则将先计算X == Y ,然后再计算Z == T The built-in || 内置|| operator is evaluated left-to-right and it short-circuits, so if X == Y is true, then by definition X == Y || Z == T 运算符从左到右进行评估,并且短路,因此,如果X == Y为true,则根据定义X == Y || Z == T X == Y || Z == T is true so Z == T is not evaluated. X == Y || Z == T为真,因此不评估Z == T

However, the || 但是, || operator can also be overloaded, and if it is overloaded it does not short circuit. 操作员也可以过载,如果过载,也不会短路。 Tf a user-defined overload of || 用户定义的||重载 is selected for the use of || 选择用于|| here, then both X == Y and Z == T are evaluated, even if X == Y is true. 在这里,即使X == Y为true,也将同时评估X == YZ == T It is rare that the || ||很少 operator is overloaded as it can lead to unintuitive code. 操作符重载,因为它可能导致代码不直观。 It's just important to remember that it doesn't behave the same way as the built-in operator. 重要的是要记住,它的行为与内置运算符的行为不同。

The first expression left to right will always be evaluated (in this case (X==Y) ), the second expression (again left to right and in this case (Z==T) ) will only be evaluated if the first is false. 从左到右的第一个表达式将始终被求值(在这种情况下(X==Y) ),仅在第一个表达式为false的情况下,才将求第二个表达式(从左到右,在这种情况下(Z==T) ) 。 This is known as Short-circuit evaluation . 这称为短路评估

X==Y will be evaluated first. X == Y将首先被评估。 If true and since the condition is an OR, nothing else on the line will be evaluated. 如果为true且由于条件为OR,则不会评估该行上的其他任何内容。

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

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