Bit-field alignment

suggest change

Bit-fields declare structure or union members that occupy a specified number of bits. Implementations typically pack them with byte-level or word-level masks. The following example is often eight bytes, but the layout is not guaranteed.

struct C
{
    short s;            /* 2 bytes */
    char  c;            /* 1 byte */
    int   bit1 : 1;     /* 1 bit */
    int   nib  : 4;     /* 4 bits padded up to boundary of 8 bits. Thus 3 bits are padded */
    int   sept : 7;     /* 7 Bits septet, padded up to boundary of 32 bits. */
};

The comments describe one possible layout, but because the standard says the alignment of the addressable storage unit is unspecified, other layouts are also possible.

An unnamed bit-field cannot be initialized or referenced. Its width must still be representable in the bit-field's type; it is not unlimited.

A zero-width bit-field cannot be given a name. It tells the implementation not to pack later bit-fields into the same addressable storage unit. Where that unit begins is implementation-defined.

Whether unsigned char is a permitted bit-field type is implementation-defined. On implementations that pack the fields of structure A into one byte, sizeof(struct A) is 1. That size is common but not guaranteed.

struct A
{
    unsigned char c1 : 3;
    unsigned char c2 : 4;
    unsigned char c3 : 1;
};

One possible layout of structure B is: the unnamed field after c1 skips 2 bits; the zero-width field after c2 starts a new storage unit, so c3 does not share that unit with c2; and c4 is followed by padding. In that layout the structure is 2 bytes. Other layouts are allowed.

struct B
{
    unsigned char c1 : 1;
    unsigned char    : 2;    /* Skips 2 bits in the layout */
    unsigned char c2 : 2;
    unsigned char    : 0;    /* Causes padding up to next container boundary */ 
    unsigned char c3 : 4;
    unsigned char c4 : 1;
};

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents