How to make functions with flag parameters? (C++)

c++, flags, function

Solution

You can define an enum specifying "single bit" values (note that the enclosing struct is acting here only as a naming context, so that you can write e.g. `MyFlags::EVEN`):

struct MyFlags{
    enum Value{
        EVEN                           = 0x01,
        ODD                            = 0x02,
        ANOTHER_FLAG                   = 0x04,
        YET_ANOTHER_FLAG               = 0x08,
        SOMETHING_ELSE                 = 0x10,
        SOMETHING_COMPLETELY_DIFFERENT = 0x20
    };
};

and then use it like this:

int CreateNum(MyFlags::Value flags){
    if (flags & MyFlags::EVEN){
        // do something...
    }
}

void main(){
    CreateNum((MyFlags::Value)(MyFlags::EVEN | MyFlags::ODD));
}

or simply like this:

int CreateNum(int flags){
    if (flags & MyFlags::EVEN){
        // do something...
    }
}

void main(){
    CreateNum(MyFlags::EVEN | MyFlags::ODD);
}

You could also simply declare integer constants, but the enum is clearer in my opinion.

Note: I updated the post to take some comments into account, thanks!

Problem

How could I make a function with flags like how Windows' CreateWindow(...style | style,...), for example, a createnum function: ``` int CreateNum(flag flags) //??? { int num = 0; if(flags == GREATER_THAN_TEN) num = 11; if(flags == EVEN && ((num % 2) == 1) num++; else if(flags == ODD && ((num % 2) == 0) num++; return num; } //called like this int Number = CreateNum(GREATER_THAN_TEN | EVEN); ``` Is this possible, and if so, how?

Original source