What is this operator: &=

无人久伴 提交于 2019-12-31 03:26:25

问题


Can someone explain what is the operator &= for?

I searched, but I got only results with & or =.


回答1:


a &= b;

Is the same as

a = a & b;

& is the "bitwise and operator", search for that.




回答2:


It's a shorthand operator which allows you to collapse

a = a & b

into

a &= b

Apart from bitwise operations on integers, &= can be used on boolean values as well, allowing you to collapse

a = a && b

into

a &= b

However, in the case of logical operation, the expanded form is short-circuiting, while the latter collapsed form does not short-circuit.

Example:

let b() be a function that returns a value and also does stuff that affects the program's state

let a be a boolean that is false

if you do

a = a && b()

the short-circuit happens: since a is false there's no need to evaluate b (and the extra computation that might happen inside b() is skipped).

On the other hand, if you do

a &= b()

the short-circuit doesn't happen: b is evaluated in any case, even when a is false (and evaluating b() wouldn't change the logical outcome), thus any extra computation that might happen inside b() does get executed.




回答3:


This

x &= y;

is equivalent to

x = x & y;

Note that & is the bitwise and operator.




回答4:


If i remember correctly it biwise operation...for example it can be used with [Flags]Enum. It check if your flag variable has specific value.




回答5:


In C#(and in most languages I think) its the bitwise assigment operator.

a &= b is equivalent of a = a & b

http://msdn.microsoft.com/en-us/library/e669ax02.aspx




回答6:


a &= b is equivalent to a = a & b



来源:https://stackoverflow.com/questions/8910623/what-is-this-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!