When to use bit-fields in C?

A quite good resource is Bit Fields in C.

The basic reason is to reduce the size used. For example if your 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 3 little flags, that should only need 3 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 obviously less error prone.

Leave a Comment