Can I use bitwise operators instead of logical ones?

前端 未结 5 1883
青春惊慌失措
青春惊慌失措 2021-01-18 04:52

Bitwise operators work on bits, logical operators evaluate boolean expressions. As long as expressions return bool, why don\'t we use bitwise operators instead

5条回答
  •  不知归路
    2021-01-18 05:06

    There is a distinct difference between || and |.

    Unlike most other operators in the language, the logical || operator explicitly specifies the order of evaluation. The first operand of || must be evaluated before the second. The second need not be evaluated at all.

    This is fundamentally different from | which behaves as most operators: the order of evaluation is unspecified, and both expressions will be evaluated. Even in the case where one operand is found to be non-zero, the other operand will still be evaluated for side effects.

    Meaning that code like f1() || f2() will always evaluate to this pseudo code:

    if(f1() != 0)
    {
      f2();
    }
    

    whereas f1() | f2() will execute both functions, in an unspecified order that the programmer can't know.

    This also means that statements like "|| is faster than |" are naive. Sure, in case of || the second operand isn't necessarily evaluated, but this comes at the cost of a branch, as well as restrictions for how the compiler is allowed to re-order the expression. Which operator that is generally faster isn't obvious.

提交回复
热议问题