What is this operator: &=

前端 未结 6 866
暖寄归人
暖寄归人 2021-01-21 16:16

Can someone explain what is the operator &= for?

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

6条回答
  •  不思量自难忘°
    2021-01-21 16:50

    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.

提交回复
热议问题