Dunaril
Dunaril

Reputation: 2795

Operator |= for a boolean in C++

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?

Upvotes: 23

Views: 36406

Answers (4)

Chris Shain
Chris Shain

Reputation: 51369

It's bitwise OR assignment, not short-circuited OR evaluation.

It is equivalent to:

result = result | TryAndDoSomething(i);

Not:

result = result || TryAndDoSomething(i);

Upvotes: 54

Mooing Duck
Mooing Duck

Reputation: 66961

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).

Upvotes: 1

Jon Purdy
Jon Purdy

Reputation: 55069

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.

Upvotes: 9

Ben Voigt
Ben Voigt

Reputation: 283803

On booleans, | yields the same result as ||, but doesn't short-circuit. The right operand of |= is always evaluated.

Upvotes: 28

Related Questions