Jeff
Jeff

Reputation: 12418

What does the |= operator mean in C++?

What does the |= operator mean in C++?

Upvotes: 25

Views: 56690

Answers (3)

Lee Netherton
Lee Netherton

Reputation: 22482

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

Upvotes: 4

Jonathan Leffler
Jonathan Leffler

Reputation: 753515

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.

Upvotes: 45

ronag
ronag

Reputation: 51255

x |= y

same as

x = x | y

same as

x = x [BITWISE OR] y

Upvotes: 10

Related Questions