What does the |= operator mean in C++?
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 means to perform a bitwise operation with the values on the left and right-hand side, and then assign the result to the variable on the left, so a bit of a short form.
%= Modulus AND assignment operator. It takes modulus using two operands and assigns the result to the left operand. C %= A is equivalent to C = C % A.
Assuming you are using built-in operators on integers, or sanely overloaded operators for user-defined classes, these are the same:
a = a | b;
a |= b;
The '|=
' symbol is the bitwise OR assignment operator. It computes the value of OR'ing the RHS ('b') with the LHS ('a') and assigns the result to 'a', but it only evaluates 'a' once while doing so.
The big advantage of the '|=' operator is when 'a' is itself a complex expression:
something[i].array[j]->bitfield |= 23;
vs:
something[i].array[i]->bitfield = something[i].array[j]->bitfield | 23;
Was that difference intentional or accidental?
...
Answer: deliberate - to show the advantage of the shorthand expression...the first of the complex expressions is actually equivalent to:
something[i].array[j]->bitfield = something[i].array[j]->bitfield | 23;
Similar comments apply to all of the compound assignment operators:
+= -= *= /= %=
&= |= ^=
<<= >>=
Any compound operator expression:
a XX= b
is equivalent to:
a = (a) XX (b);
except that a
is evaluated just once. Note the parentheses here - it shows how the grouping works.
x |= y
same as
x = x | y
same as
x = x [BITWISE OR] y
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