What is &= and |=

前端 未结 7 1108
独厮守ぢ
独厮守ぢ 2021-01-18 07:31

I was going through some VC++ code in a large code-base and came across this:

    if (nState & TOOL_TIPS_VISIBLE)
        nState &= ~TOOL_TIPS_VISI         


        
相关标签:
7条回答
  • 2021-01-18 07:45

    & and | are similar to && and ||, only they works in bitwise fashion. So now you could imagine &= and |= works similar to +=. That is x &= y; ==> x = x & y;

    0 讨论(0)
  • 2021-01-18 07:47

    What hasn't been mentioned is that both &= and |= operators can be overloaded. Therefore, the code you posted depends on the type of nState (although it's quite clearly an int, so most probably this doesn't apply here). Overloading &= does not implicitly overload &, so in this case

    x &= y might not be the same as x = x & y
    

    It might also depend on what TOOL_TIPS_VISIBLE is.

    struct s{
       int x;
    };
    
    void operator &= (int& x, s y)
    {
       x = 0;
    }
    

    Now whenever you do:

    s TOOL_TIPS_VISIBLE;
    x &= TOOL_TIPS_VISIBLE;
    

    x will become 0. Again, highly unlikely, but good to know nevertheless.

    All other answer probably apply here, but this is worth considering.

    0 讨论(0)
  • 2021-01-18 07:52

    Its bitwise and or

    in the first case the flag (bit) is turned off

    nState &= ~TOOL_TIPS_VISIBLE
    

    in the second case the flag is turned on

    nState |= TOOL_TIPS_VISIBLE
    
    0 讨论(0)
  • 2021-01-18 07:56

    x &= y is the same as x = x & y
    x |= y is the same as x = x | y

    0 讨论(0)
  • 2021-01-18 08:01

    Yes. &= is to & what += is to +

    0 讨论(0)
  • 2021-01-18 08:02

    x &= y means x = x & y. So yes you're right.

    0 讨论(0)
提交回复
热议问题