10

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
}

1 Answer 1

18

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.

Sign up to request clarification or add additional context in comments.

5 Comments

If I have the before and after values of all options - is it possible to know which options were toggled?
Maybe an example would be better:
originalOptions = option1 | option 2; //After toggling laterOptions = option1 | option3; I understand that option2 was "turned off"
@AvnerBarr XOR to the rescue again... oldOptions ^ newOptions will also tell you which ones were flipped.
and then & with each of the option names ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.