When to use bit-fields in C

A quite good resource is Bit Fields in C.

The basic reason is to reduce the used size. For example, if you write:

struct {
    unsigned int is_keyword;
    unsigned int is_extern;
    unsigned int is_static;
} flags;

You will use at least 3 * sizeof(unsigned int) or 12 bytes to represent three small flags, that should only need three bits.

So if you write:

struct {
    unsigned int is_keyword : 1;
    unsigned int is_extern : 1;
    unsigned int is_static : 1;
} flags;

This uses up the same space as one unsigned int, so 4 bytes. You can throw 32 one-bit fields into the struct before it needs more space.

This is sort of equivalent to the classical home brew bit field:

#define IS_KEYWORD 0x01
#define IS_EXTERN  0x02
#define IS_STATIC  0x04
unsigned int flags;

But the bit field syntax is cleaner. Compare:

if (flags.is_keyword)

against:

if (flags & IS_KEYWORD)

And it is obviously less error-prone.

Leave a Comment