简体   繁体   中英

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))
{
 //code here
}

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

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 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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