C++ meaning |= and &=

后端 未结 7 1441

I have a part of code that contains the following functions:

void Keyboard(int key)
{
    switch (key) {
    case GLFW_KEY_A: m_controlState |= TDC_LEFT; bre         


        
相关标签:
7条回答
  • 2020-12-20 08:35

    Also I think it should be explained what these operators do and are used this way.

    m_controlState serves as flags, which means it contains in binary form which of the keys are pressed. For example if the values of tds constants are chosed like this:

    TDS_LEFT             = 0x00001
    TDS_RIGH = 0x01 << 2 = 0x00010 
    TDS_UP   = 0x01 << 3 = 0x00100
    TDS_DOWN = 0x01 << 4 = 0x01000
    

    Then in single integer you can store information which options are set. To do that you just have to check if bit that corresponds on each setting is 1 or 0.

    So to set TDS_LEFT option, you have to OR the current state with 0x00001( which is TDS_LEFT), so in code

    m_controlState = m_controlState | TDS_LEFT
    

    which is the same as

    m_controlState |= TDS_LEFT.
    

    To unset TDS_LEFT option you have to AND it with ~TDS_LEFT. So

    m_controlState = m_controlState & ~TDS_LEFT
    

    which is the same as:

    m_controlState &= ~TDS_LEFT
    

    You can also check: How to use enums as flags in C++?. Hope that makes it clearer.

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