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
CodePudding user response:
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.
CodePudding user response:
Bitwise and logical operators are quite different:
- Logical operators work on the logical values of the variables and give back
true
orfalse
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;
}
}