开发者

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? Also, do they both get evaluated?

if( (X==Y) || (Z==T))
{
 开发者_JAVA百科//code here
}


They're evaluated left-to-right and if the first one is true the expression short-circuits and the second one is not evaluated.


If the built-in || operator is used, then X == Y will be evaluated before Z == T is evaluated. 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 is true so Z == T is not evaluated.

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. 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. This is known as Short-circuit evaluation.


X==Y will be evaluated first. If true and since the condition is an OR, nothing else on the line will be evaluated.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜