Bitfields

The maximum width of bitfields is 32 bits. The default allocation unit is a byte. The compiler uses words only if a bitfield is wider than 8 bits, or if using bytes would cause a gap bigger than the limit specified by the -bfield_gap_limit option. The default allocation order within the allocation unit is from the least significant bit up to the most significant one in the order of bitfield declaration (that is, the first bitfield in the order of declaration will be leftmost in the allocation unit). Allocation units (either bytes or words) are always allocated in memory from the smallest to the highest address (that is, the first allocation unit will be at the smallest address in memory).

The following figure illustrates this allocation scheme:

Figure 1. Allocation of Six Bitfields
Allocation of Six Bitfields

The compiler also supports unnamed bitfields - which can be used for padding. Unnamed bitfield of width 0 forces alignment of the next bitfield to word boundary (no further bits will be placed in the current word), even if the current allocation unit is a byte.

Note: Unnamed bitfields cannot be initialized.

The following example demonstrates how to use unnamed bitfields for padding:

Listing: Example - Using Unnamed Bitfields for Padding
typedef struct {
        unsigned char a : 3;

        unsigned char : 2;

        unsigned char c: 3;

} SomeStruct;

SomeStruct s;

Assuming we initialize the fields of s as follows:

  s.a = 6; s.c = 7;  

we get this memory layout for s: E6.

The example below shows how zero-width unnamed bitfields work.

Listing: Example - Zero-width Unnamed Bitfields
typedef struct {
        unsigned char a : 3;

        unsigned char : 0;

        unsigned char c: 3;

} SomeStruct;

SomeStruct s;

Assuming we initialize the fields of s as follows:

  s.a = 6; s.c = 7;  

we get this memory layout for s: 00 06 07.

For more information, refer to the following topics: