Bitwise OR and logical OR operators. Who cares?

Is there any functional difference between logical and bitwise operators in the following code? What are the reasons for this or that use?

typedef unsigned char BOOLEAN; void orOperatorsComparison(BOOLEAN bBar, BOOLEAN bFoo) { BOOLEAN bLogicalOr = (bFoo || bBar); BOOLEAN bBitwiseOr = (bFoo | bBar); ... } 
+6
source share
6 answers

What does support mean?

If this is logical or what you mean, then of course you should always use || , since it is a logical, logical, or operator.

This makes it possible to short circuit, but it does not matter much in the code, it is simple.

I would think that this is odd and strange (and due to a fix) if bitwise or used when the point does not manipulate bits.

+9
source

Boolean || there will be a short circuit: if the first operand is true , the second will never be evaluated. On the contrary, bitwise | always evaluates both arguments.

+7
source

Other answers have already talked about short circuits (but this is not a problem in your specific code). But there is one key difference.

If for some reason your input values ​​are not in [0,1], then a bitwise OR will give you an answer that also cannot be in [0,1]. Logical OR is guaranteed to give you 0 or 1.

For this reason, you should choose a logical OR. Your intention is (presumably) to control logical values, so using an illogical operator is illogical. *


* Pun is definitely intended.
+7
source

In this particular case, no, there is no difference in the result:

 1 || 0 == 1 1 | 0 == 1 

all truth tables apply here.

If you are talking about how we came to the result, then there may be a difference. Using || you have a short circuit mechanism:

 BOOLEAN bFooBar = (bFoo||bBar) // if bFoo is TRUE, we never look at bBar // vs BOOLEAN bFooBar = (bFoo|bBar) // where we take into account both values 

So long and short, yes, you may not use logical and bitwise operators correctly in some cases and get the same results, but why would you ever do that? If you know that this is wrong, and you know that it can lead to bad things, it’s hard to find mistakes, use the tools that the language provides for the tasks that they should do.

+2
source

Bitwise or operator never closes when boolean. That is, if bFoo true, bBar never evaluated.

+1
source

Is there any functional difference between the logical and bitwise operators in the following case?

Yes, there is (lazy eval, as others have pointed out).

Any reason to support one or the other?

If in some way they were equivalent, then to use logical operators it would be better to preserve the semantics intended for this type. See Also: Principle of Least Surprise .

+1
source

All Articles