C++ short-circuiting of booleans

前端 未结 8 1986
生来不讨喜
生来不讨喜 2020-11-28 16:05

I\'m new to c++ and am curious how the compiler handles lazy evaluation of booleans. For example,

if(A == 1 || B == 2){...}

If A does equal

8条回答
  •  爱一瞬间的悲伤
    2020-11-28 16:34

    Unless the || operator is overloaded, the second expression will not be evaluated. This is called "short-circuit evaluation."

    In the case of logical AND (&&) and logical OR (||), the second expression will not be evaluated if the first expression is sufficient to determine the value of the entire expression.

    In the case you described above:

    if(A == 1 || B == 2) {...}
    

    ...the second expression will not be evaluated because

    TRUE || ANYTHING, always evaluates to TRUE.

    Likewise,

    FALSE && ANYTHING, always evaluates to FALSE, so that condition will also cause a short-circuit evaluation.

    A couple of quick notes

    • Short circuit evaluation will not apply to overloaded && and || operators.
    • In C++, you are guaranteed that the first expression will be evaluated first. Some languages do not guarantee the order of evaluation and VB doesn't do short-circuit evaluation at all. That's important to know if you are porting code.

提交回复
热议问题