Search code examples
cenumstypedef

Toggling enum values as bit flags


I have a certain set of available enumed options

typdef enum { 
option1 = 1 << 0,
option2 = 1 << 1,
option3 = 1 << 2,
} availableOptions;

I want to toggle them off and on according to an input from the user before executing them.

For instance:

// iniatially set to all options
myOption = option1 | option2 | option3;

// after some input from the user

void toggleOption1()
{
  // how can I toggle an option that was already set without impacting the other options
}

Solution

  • Use bit-wise XOR:

    void toggleOption1()
    {
        myOption ^= option1;
    }
    

    The caret symbol ^ is the bit-wise XOR operator. The statement:

    a ^= b;
    

    flips only the bits in a where the corresponding bit in b is set. All other bits are left alone.