Operator | = for boolean in C ++

I came across the following construct in C ++:

bool result = false;
for(int i = 0; i<n; i++){
  result |= TryAndDoSomething(i);
}

      

I assumed this |=

was a shortcut for the OR operator and that it result

would end up equal true

if at least one of those calls TryAndDoSomething

returned true

.

But now I'm wondering if more than one call can actually return true

. Indeed, if we continue the operation as:

result = result || TryAndDoSomething(i);

      

Then the method will only be called if return evaluates to false

, that is, if no other call before returning true

. This way, after one call that returns true

, no other call will be made.

Is this the correct interpretation?

+8


source to share


4 answers


In a boolean, |

it gives the same result as ||

but does not close. The correct operand is |=

always evaluated.



+9


source


This is a bitwise OR assignment, not a short-circuit OR evaluation. This is equivalent to:

result = result | TryAndDoSomething(i);

      



not

result = result || TryAndDoSomething(i);

      

+13


source


The only difference in this context between x |= f()

(bitwise OR) and x = x || f()

(logical OR) is that the latter is short-circuited. In the first case, it f()

will be executed n

once, unless, of course, f()

it throws an exception, but that's another story.

The version ||

f()

will no longer be called once x

becomes true

. C ++ does not have an operator ||=

, but it is important to understand that because of this, |=

and ||=

(if it existed) would have different semantics. |=

is not just a replacement for the absent one ||=

.

As a side note, if you use bool

, the bitwise operation is safe as the standard states that true

both are false

converted to integers 1

and 0

respectively. So the only difference in this case is impatient and lazy appraisal.

+2


source


result |= Try()

not suitable for result = result | Try();

. The operator ||

you seem to understand, but the operator is |

completely different. This name is bitwise or (as opposed to boolean or). It has the same effect as if it was executing a=a||b

for every bit of the operands and did not have fast escape information that was logical and / or having. (It's also insanely fast, just as fast or faster than adding). Other bitwise operations are &

(bitwise and: a=a&&b

for each bit) and ^

(bitwise xor: a=(a!=b)

for each bit).

0


source







All Articles