How do flags work in C?

Justin Meiners picture Justin Meiners · Sep 4, 2010 · Viewed 15.7k times · Source

Recently I have come across several examples of "flags" in C and C++, and I don't quite understand how they work. After looking at some source code I noticed that often flag values are defined in hexadecimal such as the following:

FLAG1 = 0x00000001,
FLAG2 = 0x00000010,

My intuitive suggests that these values are being combined. Do flags work by combining all the flags values into one int? If I had used both of these like FLAG1 | FLAG2 would the result be 0x00000011?

Do I need to create enums with bit offsets or can I use ascending integers Like:

FLAG1 = 1;
FLAG2 = 2;

Answer

jtbandes picture jtbandes · Sep 4, 2010

You need to offset the bits, otherwise there's no way to extract the individual flags. If you had flags corresponding to 1, 2, 3, & 4, and a combined value of 5, how could you tell if it was 2 & 3 or 1 & 4?

You can also do it this way, for example:

enum {
    FIRST = 1 << 0, // same as 1
    SECOND = 1 << 1, // same as 2, binary 10
    THIRD = 1 << 2, // same as 4, binary 100
    FOURTH = 1 << 3 // same as 8, binary 1000
};

Then you combine flags like so:

int flags = FIRST | THIRD | FOURTH;

And you extract them like this:

if (flags & THIRD) { ...