What does the |= operator mean in C++?
x |= y
same as
x = x | y
same as
x = x [BITWISE OR] y
It is a bitwise OR compound assignment.
In the same way as you can write x += y
to mean x = x + y
you can write x |= y
to mean x = x | y
, which ORs together all the bits of x
and y
and then places the result in x
.
Beware that it can be overloaded, but for basic types you should be ok :-)
You can try using SymbolHound: the search engine for programmers to search sites like SO for symbols such as this. Here are the results for |= on SymbolHound. -Tom (cofounder SH)
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.