Frage

Assume code snippet

bool a;
a = true;
a |= mayRun();

a = false;
a |= mayRun();

in which case is mayRun() being executed?

All explanations tell me, that a |= b; is equivalent to a = a | b;

But it cannot be the same as the example arr[i++] |= b; indicates.

War es hilfreich?

Lösung 2

It's always executed. Note that a |= b is indeed a shorthand for a = a | b (only evaluating a once). In particular, it's not a shorthand for a = a || b.

This means it does not provide the short-circuiting behaviour of boolean operators, so the b is always evaluated.

Using these shorthand assignment forms with bool variables is dangerous, precisely because the sematnics are non-obvious. &= is actually even worse. Compare this:

int two() { return 2; }

int main()
{
  bool b = true;
  b = b && two();
  assert(b);  //OK
}

with this:

int two() { return 2; }

int main()
{
  bool b = true;
  b &= two();
  assert(b);  //FAILS!!
  // b &= two(); was actually b = 1 & 2, which is 0 !
}

In short, avoid using |= and &= with boolean variables.

Andere Tipps

It will always be executed because short-circuiting is not applicable to bitwise operations (only applicable to logical operations such as && and ||).

Note that this misconception can lead to nasty errors - the developer will assume there is short-circuiting but there's none and all the expression parts are executed at all times and that alters the program logic.

in which case is mayRun() being executed?

It will always be executed.

Perhaps you were expecting |= to perform short-circuiting, but it doesn't: that only happens with the logical operators && and ||, when the result can be determined from just the first operand. There are no logical compound-assignment operators like ||=, so short-circuiting will never happen in an assignment expression.

All explanations tell me, that a |= b; is equivalent to a = a | b;

Almost; but whatever explanations you've been reading have missed out an important detail.

But it cannot be the same as the example arr[i++] |= b; indicates.

Indeed, there is a difference, as specified by C++11 5.17/7:

The behavior of an expression of the form E1 op = E2 is equivalent to E1 = E1 op E2 except that E1 is evaluated only once.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top