1


In an example I saw these operators (|= and &=) but it wasn't explained. I was looking on Google about it, but I found only results related to the "classic" = operator.
So I would like to know what are these operators doing. Can somebody explain it to me ?

1

4 Answers 4

6

They are simply shorthand assignments like +=. The following are equivalent:

s |= t; s = s | t; 

And these are also equivalent.

s &= t; s = s & t; 

For more information on those operators, you can see the MSDN Docs on | and & Operator.

Sign up to request clarification or add additional context in comments.

5 Comments

Wow ! That was fast ! Thank you for the explain and the links ;-) Sorry for this noob question.
They aren't strictly equivalent. The |= operator will ensure that the left hand side is only evaluated once, not twice. It's still an appropriate way to conceptualize it, even though they're not exactly the same.
@Servy: Thanks for pointing that out. Aren't they still functionally equivalent, even if the underlying OP-codes might translate slightly differently?
@mellamokb No, they're not. In your example s might not just be a local variable. It could be an expression that results in side effects. The |= case those side effects only occur once, in the following example they would occur twice.
@Servy: Gotcha. Though that's true with a lot of operations if you don't use good programming practices. I would consider side effects resulting from modifying a local variable/property a red flag.
1

|= and &= are assignment operators related to the | (bitwise or) and & (bitwise and) operators.

Comments

1

They perform bitwise-OR |= operations and bitwise-AND &= operations with the result being stored in the lValue. They're the same as | and &, but store the result in the lValue analogous to the difference between + and += or - and -=.

Comments

0

well &= is the same like i+=, in other words

x&=2 is a short form of x=x & 2

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.