Can I use bitwise operators instead of logical ones?

前端 未结 5 1708
青春惊慌失措
青春惊慌失措 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:25

    The answer is yes, you can. The question is why would you want to? I can name a few reasons you shouldn't:

    1. It can be very confusing for other programmers.
    2. It's easy to miss that one of the operands is not of type bool, which can lead to subtle bugs.
    3. The order of operand evaluation is undefined.
    4. It messes up the short-circuiting rule.

    To illustrate the last point:

    bool f1() {
        cout << "f1" << endl;
        return true;
    }
    
    bool f2() {
        cout << "f2" << endl;
        return true;
    }
    
    int main() {
        if (f1() || f2()) {
            cout << "That was for ||" << endl;
        }
        if (f1() | f2()) {
            cout << "That was for |" << endl;
        }
        return 0;
    }
    

    It prints:

    f1
    That was for ||
    f1
    f2
    That was for |
    

    Assuming f2 may have significant side effects (if (okToDestroyWorld && destroyWorld()) ...), the difference can be enormous. It wouldn't surprise a Java programmer (where | and || actually defined for booleans by the language specification), but it is not a usual practice in C++.

    I can think of just one reason to use a bitwise operator for booleans: if you need XOR. There is no ^^ operator, so if (a ^ b) is fine as long as both a and b are bool and there are no side effects involved.

提交回复
热议问题