Search code examples
c++enumerationenumeratorbitwise-or

Using bitwise or operator in switch case


I have enum,

enum ENUM_MSG_TEXT_CHANGE {COLOR=0,SIZE,UNDERLINE};

    void Func(int nChange)
    {
bool bColor=false, bSize=false;
    switch(nChange)
    {
    case COLOR:bColor=true;break;
    case SIZE:bSize=true;break;
    case COLOR|SIZE:bSize=true; bColor=true;break;
    }
    }

case SIZE: and case COLOR|SIZE: both gives value 1, so I am getting the error C2196: case value '1' already used. How to differentiate these two cases in switch case?

Thanks


Solution

  • If you want to make a bitmask, every element of your enum has to correspond to a number that is a power of 2, so it has exactly 1 bit set. If you number them otherwise, it won't work. So, the first element should be 1, then 2, then 4, then 8, then 16, and so on, so you won't get overlaps when orring them. Also, you should just test every bit individually instead of using a switch:

    if (nChange & COLOR) {
        bColor = true;
    }
    if (nChange & SIZE) {
        bSize = true;
    }