Chainable boolean flags - what are they called?

Viewed 55

Frameworks I've seen before allow to pass a chain of multiple constants via a single parameter like So, I believe:

foo(FLAG_A | FLAG_B | FLAG_C);

They act like boolean so the function knows which flags have been given.

Now I want to implement something like that.

What is this concept called?

3 Answers

It's based on binary-ORing. Normally, each of the symbolic constants will be just one distinct bit, e.g., as in:

enum {
   FLAG_A = 1,
   FLAG_B = 1<<1,
   FLAG_C = 1<<2,
};

so that you can than add them together with |, test for each individual one with & and subtract two such flag sets with & ~.

In .Net, these are defined by an enum using the FlagsAttribute:

[Flags()]
public enum Foo
{
     Bit1 = 1,
     Bit2 = 2,
     Bit4 = 4,
     Bit8 = 8,
     etc.
 }

// Or define using explicit binary syntax
[Flags()]
public enum Foo
{
     Bit1 = 0b_0000_0001,
     Bit2 = 0b_0000_0010,
     Bit4 = 0b_0000_0100,
     Bit8 = 0b_0000_,
     etc.
 }

And to utilise:

SomeFunction(Foo.Bit1 | Foo.Bit4 | etc);

I would suggest that your current name (Flags) seems to be the most appropriate definition, at least in this context.

Apparently "flags and bitmasks" are the right keywords to find more about this. "Flags" alone didn't before. Great thanks for the explanatory answers nevertheless!

Related