I’m not very used to programming with flags, but I think I just found a situation where they’d be useful:
I’ve got a couple of objects that register themselves as listeners to certain events. What events they register for is dependent on a variable that is sent to them when they are constructed. I think a nice way to do this would be to send bitwise OR connected variables, like such: TAKES_DAMAGE | GRABBABLE | LIQUID, etc. Then, in the constructor, the object can check what flags are set and register it self as listener for the ones that are.
But this is where I get confused. Preferably, the flags would be in an enum. But that is also a problem. If we have got these flags:
enum
{
TAKES_DAMAGE,/* (0) */
GRABBABLE, /* (1) */
LIQUID, /* (2) */
SOME_OTHER /* (3) */
};
Then sending the flag SOME_OTHER (3) will be the same as sending GRABBABLE | LIQUID, will it not?
How exactly do you deal with this stuff?
Your enumeration needs to be powers of two :
Or in a more readable fashion :
Why ? Because you want to be able to combine flags with no overlapping, and also be able to do this:
… Which works if the enumeration values look like this :
So, say you’ve set
myVartoGRABBABLE | TAKES_DAMAGE, here’s how it works when you need to check for the GRABBABLE flag:If you’d set
myVartoLIQUID | SOME_OTHER, the operation would have resulted in :