Switching enum values ​​as bit flags

I have a specific set of enumerated options available.

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

I want to disable them and enable according to user input before executing them.

For example:

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

// after user input

void toggleOption1()
{
  // how can I toggle an option that was already set without impacting the other options
}
+4
source share
1 answer

Use bitwise XOR:

void toggleOption1()
{
    myOption ^= option1;
}

The carriage character ^is an XOR bitwise operator. Statement:

a ^= b;

flips only bits in awhere the corresponding bit in is set b. All other bits remain valid.

+5
source

All Articles