Search code examples
c++operatorsbitwise-operators

Boolean bitwise and logical operators


I Have two booleans with OR operation between them.

According to my understanding, I can use bitwise or logical operators and it will have the same effect:

bitwise:

bool first = true, second = false;
first = first | second;

logical:

bool first = true, second = false;
first = first || second;

Is there any difference? What's the better way?


Solution

  • As noted in the comments, you should use logical operators when you're doing logic and bitwise operators when doing bitwise operations.

    One of the main differences among these is that C++ will short-circuit the logical operations; meaning that it will stop evaluating the operands as soon as it's clear what the result of the operation is.

    As an example, this code:

    bool foo() {
        std::puts("foo");
        return true;
    }
    
    bool bar() {
        std::puts("bar");
        return true;
    }
    
    //...
    
    auto const res = foo() || bar();
    

    will only output:

    foo
    

    Function bar won't be evaluated as, in this case, evaluating foo is enough to know the result of expression foo() || bar() is true.