[C++] Bit-flags


Bit-flags are used in C and C++ to save memory by allowing you to pack multiple boolean variables into a single integer variable.

While they are very good at this, the syntax for using them isn’t exactly the easiest to read, so I thought I’d share a trick we use at work to deal with bit-flags.

The Code

struct Flags8
		uint8_t     allFlags;
			bool    flag1 : 1;
			bool    flag2 : 1;
			bool    flag3 : 1;
			bool    flag4 : 1;
			bool    flag5 : 1;
			bool    flag6 : 1;
			bool    flag7 : 1;
			bool    flag8 : 1;

The code above shows a struct containing a union between an 8-bit unsigned integer, and another struct containing a series of bit-wide booleans (that’s what the : 1 does).

The union means that the allFlags variable contains the combined bit-flag value of all the booleans in the inner struct. This means that you can only have as many flags in your struct as you can fit bits in your integer; for an 8-bit integer, this is 8; for a 16-bit integer it would be 16; for a 32-bit integer, it would be 32.

You would use the above struct like so.

Flags8 flags8;
flags8.allFlags = 0;
flags8.flag2 = true;
assert(sizeof(Flags8) == sizeof(uint8_t));
comments powered by Disqus