What is happening in an “If(..||..)” and “If(…&&…)” construct internally?

后端 未结 6 1987
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-15 18:29

I was just wondering what happens inside of an \"if OR\" and \"if AND\". I have a feeling that it\'s just syntactic sugar to use &

6条回答
  •  感情败类
    2020-12-15 18:59

    || and && are conditional-operators. They're also operators, like other operators you might know. (e.g. +, *, ...)

    Their behavior is similar to logical-operators, | and &. They receive two bool type variables and return bool value in this way:

    // If one of them is true, the return value is true. Otherwise, it's false.
    true  | true  == true
    true  | false == true
    false | true  == true
    false | false == false
    // If both of them are true, the return value is true. Otherwise, it's false.
    true  & true  == true
    true  & false == false
    false & true  == false
    false & false == false
    

    However, as for conditional-operators, there's a bit difference: short-circuit.

    Suppose this code:

    bool func1() { .. }
    bool func2() { .. }
    
    bool b1 = func1() || func2();
    bool b2 = func1() && func2();
    

    If func1() returns true, b1 becomes true regardless of what func2() returns. Therefore, we don't need to call func2() and actually don't. If func1() returns false, the same thing is applied to b2. This behavior is called short-circuit.


    Now, let's think about your example.

    if (a || b || c)
        DoSomething();
    

    It's equal to

    bool value = a || b || c;
    if (value)
        DoSomething();
    

    Since the order of evaluation of conditional operators is left-to-right, it's equal to

    bool value = (a || b) || c;
    if (value)
        DoSomething();
    

提交回复
热议问题