Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

operators

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

like image 649
Jeff Avatar asked Nov 18 '10 17:11

Jeff


People also ask

What is the meaning of |= operator?

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.

What does &= mean in C programming?

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.

What does %= mean in C?

%= 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.


2 Answers

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.

like image 100
Jonathan Leffler Avatar answered Oct 25 '22 13:10

Jonathan Leffler


x |= y

same as

x = x | y

same as

x = x [BITWISE OR] y
like image 21
ronag Avatar answered Oct 25 '22 13:10

ronag