1

What is the difference between bitwise and logical OR operations when it comes to boolean variables in C++? In the integer domain, it is clear but when it comes to boolean is there any performance advantage or behavioral change between both of them?

bool VAR = TRUE , BOOL VAR2= TRUE

Is there a difference in VAR | VAR2 & VAR || VAR2

Justin M
  • 29
  • 3

2 Answers2

5

For performance differences, logical OR short-circuits (e.g., in op1 || op2, if op1 evaluates to true, op2 is not evaluated), but bit-wise doesn't. This also creates a behavior difference:

if (op1 == nullptr || fn(op1)) { /* ... */ }

This code will never call fn with nullptr because of the short-circuit behavior. On the other hand, if the logical OR was replaced with bit-wise, fn would always be called. If fn has side effects or undesirable behavior when called with nullptr, this creates a behavior difference.

Mitchell
  • 366
  • 3
  • 9
  • 1
    It is worth noting that the above is equivalent to `if (op1 == nullptr) if (fn(op1))`, as in it will have two branches in the generated code. `if ((x == 0) | (y == 0))` on the other hand will always compare `x` and `y` but only do one branch. For simple condition the short circuiting of a logical or can often cost more than evaluating the second condition. As always *benchmark before optimizing*. – Goswin von Brederlow May 17 '22 at 08:36
  • Agree, premature optimization is the root of all evil. Hadn't thought of the extra branch instruction generation though! – Mitchell May 18 '22 at 05:58
2

Bitwise and logical operators are quite different:

  • Logical operators work on the logical values of the variables and give back true or false which are logical values
  • Bitwise operators work on the single bits of the variables

Briefly the bitwise operator consider the single bits of 2 varibales: & operation between 2 bitmasks gives back a bitmask where the compared bit is 1 if both the relative bits in the original mask are 1; | operation between 2 bitmasks gives back a bitmask where the compared bit is 1 if at least one of the relative bits in the original mask is 1.

The result of a bitwise peration depends on the size of a variable and its representation in bits. I made a little exercise trying to make bitwise operation on bool variables and you can run it on your machine. I think the result depends on the compiler and the architecture; anyway in my test the size of bool is 1 byte (8 bits) and in the case it's true just the first bit is 1:

#include <iostream>

int main()
{
    bool b1 = true;
    bool b2 = true;

    std::cout << "size of bool:" << sizeof(bool) << std::endl;

    for (int i = 0; i < 8 * sizeof(bool); i++)
    {
        std::cout << "bitwise operation | on bit:" << i << " result:" << (b1 | (1 << i)) << std::endl;
        std::cout << "bitwise operation & on bit:" << i << " result:" << (b1 & (1 << i)) << std::endl;
    }
}
Marco Beninca
  • 605
  • 4
  • 15