I stumbled upon the following construction in C++:
bool result = false;
for(int i = 0; i<n; i++){
result |= TryAndDoSomething(i);
}
I supposed that this |=
was a shortcut for the OR operator, and that result
would equal true
in the end if at least one of these calls to TryAndDoSomething
had returned true
.
But now I am wondering if more than one call can actually return true
. Indeed if we extend the operation as:
result = result || TryAndDoSomething(i);
Then the method will be called only if return evaluated to false
, that is, if no other call before returned true
. Thus after one call returning true
, no other call will be done.
Is this the correct interpretation?
|= is analogous to operators like += and -= in that it will perform a bitwise OR on the two operands then store the result in the left operator.
The bitwise OR assignment operator ( |= ) uses the binary representation of both operands, does a bitwise OR operation on them and assigns the result to the variable.
It's bitwise OR assignment, not short-circuited OR evaluation.
It is equivalent to:
result = result | TryAndDoSomething(i);
Not:
result = result || TryAndDoSomething(i);
On booleans, |
yields the same result as ||
, but doesn't short-circuit. The right operand of |=
is always evaluated.
The only difference in this context between x |= f()
(bitwise OR) and x = x || f()
(logical OR) is that the latter is short-circuiting. In the former, f()
will be executed n
times—unless of course f()
throws an exception, but that’s another story.
In the ||
version, f()
will no longer be called once x
becomes true
. C++ does not have a ||=
operator, but it is important to understand that |=
and ||=
(if it existed) would have different semantics because of this. |=
is not just a replacement for the missing ||=
.
As a side note, provided you are using bool
, the bitwise operation is safe, because the standard specifies that true
and false
convert to the integers 1
and 0
, respectively. So the only difference in this case is eager versus lazy evaluation.
result |= Try()
is short for result = result | Try();
. The ||
operator you seem to understand, but the |
operator is quite different. It's name is bitwise or (as opposed to logical or). It has the same affect as if it performed a=a||b
on each bit of the operands, and doesnt have the quick-bailout thing that logical and/or have. (It's also crazy fast; as fast or faster than addition). The other bitwise operations are &
(bitwise and: a=a&&b
on each bit), and ^
(bitwise xor: a=(a!=b)
on each bit).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With