Search code examples
c++bit-manipulationbox2dbitwise-operators

C++ meaning |= and &=


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; break;
    case GLFW_KEY_D: m_controlState |= TDC_RIGHT; break;
    case GLFW_KEY_W: m_controlState |= TDC_UP; break;
    case GLFW_KEY_S: m_controlState |= TDC_DOWN; break;
    default: Test::Keyboard(key);
    }
}

void KeyboardUp( int key)
{
    switch (key) {
    case GLFW_KEY_A: m_controlState &= ~TDC_LEFT; break;
    case GLFW_KEY_D: m_controlState &= ~TDC_RIGHT; break;
    case GLFW_KEY_W: m_controlState &= ~TDC_UP; break;
    case GLFW_KEY_S: m_controlState &= ~TDC_DOWN; break;
    default: Test::Keyboard(key);
    }
}

I know what a switch case is but I don't understand what these parts do.

m_controlState |= TDC_LEFT
m_controlState &= ~TDC_LEFT

m_controlState is an int. The GFLW_KEY's also refer to an int value.

Could someone explain what these parts do? An example with input values and results would be nice.

Not equal to the linked question because I also ask about &=


Solution

  • 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.