Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do flags work in C?

Tags:

c++

c

integer

flags

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;
like image 586
Justin Meiners Avatar asked Sep 04 '10 19:09

Justin Meiners


1 Answers

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) { ...
like image 176
jtbandes Avatar answered Sep 19 '22 15:09

jtbandes