...
Consequently, it is impossible to write portable code that makes assumptions about the layout of bit-field structures.
Non-Compliant Code Example (
...
Alignment)
Bit-fields can be used to allow flags or other integer values with small ranges to be packed together to save storage space. Bit-fields can improve the storage efficiency of structures. Compilers typically allocate consecutive bit-field structure members into the same int
-sized storage, as long as they fit completely into that storage unit. However, the order of allocation within a storage unit is implementation-defined. Some implementations are "right-to-left": the first member occupies the low-order position of the storage unit. Others are "left-to-right": the first member occupies the high-order position of the storage unit. Calculations that depend on the order of bits within a storage unit may produce different results on different implementations.
Consider the following structure made up of four 8-bit bit-field members.
Code Block |
---|
struct bf { unsigned m1 : 8; unsigned m2 : 8; unsigned m3 : 8; unsigned m4 : 8; }; /* 32 bits total */ |
Right-to-left implementations will allocate struct bf
as one storage unit with the this format:
Code Block |
---|
m4 m3 m2 m1 |
Conversely, left-to-right implementations will allocate struct bf
as one storage unit with the this format:
Code Block |
---|
m1 m2 m3 m4 |
...
Code Block | ||
---|---|---|
| ||
struct bf { unsigned m1 : 8; unsigned m2 : 8; unsigned m3 : 8; unsigned m4 : 8; }; /* 32 bits total */ void function() { struct bf data; data.m1 = 0; data.m2 = 0; data.m3 = 0; data.m4 = 0; char* ptr = (char*) &data; (*ptr)++; /* could increment data.m1 or data.m4 */ } |
Compliant Solution (
...
Alignment)
This code is explicit about the fields it modifies.
Code Block | ||
---|---|---|
| ||
struct bf { unsigned m1 : 8; unsigned m2 : 8; unsigned m3 : 8; unsigned m4 : 8; }; /* 32 bits total */ void function() { struct bf data; data.m1 = 0; data.m2 = 0; data.m3 = 0; data.m4 = 0; data.m1++; } |
Non-Compliant Code Example (
...
Overlap)
In this non-compliant example, assuming eight bits to a byte, if bit-fields of six and four bits are declared, is each bit-field contained within a byte or are they be the bit-fields split across multiple bytes?
...
In the above example, if each bit-field lives within its own byte, then m2 (or m1, depending on alignment) is incremented by 1. If the bit-fields are indeed packed across 8-bit bytes, then m2 might be incremented by 4.
Compliant Solution (
...
Overlap)
Code Block | ||
---|---|---|
| ||
struct bf { unsigned m1 : 6; unsigned m2 : 4; }; void function() { struct bf data; data.m1 = 0; data.m2 = 0; data.m2 += 1; } |
...