Bit-fields can be used to allow flags or other integer values with small ranges to be packed together to save storage space.
For bit-fields, it is implementation-defined whether the specifier int
designates the same type as signed int
or the same type as unsigned int
. Also, C99 requires that "If an int
can represent all values of the original type, the value is converted to an int
; otherwise, it is converted to an unsigned int
."
In the following example:
struct { unsigned int a: 8; } bits = {255}; int main(void) { printf("unsigned 8-bit field promotes to %s.\n", (bits.a << 24) < 0 ? "signed" : "unsigned"); }
The type of the expression (bits.a << 24) is compiler dependent and may be either signed or unsigned depending on the compiler's interpretation of the standard.
The first interpretation is that when this value is used as an rvalue (e.g., lvalue = rvalue), the type is "unsigned int
" as declared. An unsigned int
cannot be represented as an int
, so integer promotions require that this be an unsigned int
, and hence "unsigned".
The second interpretation is that this is an 8-bit integer. As a result, this eight bit value can be represented as an int
, so integer promotions require that it be converted to int
, and hence "signed".
This also has implications for signed long long
and unsigned long long
types. For example, gcc will also interpret the following as an eight bit value and promote it to int
:
struct { unsigned long long a:8; } ull = {255};
The following attributes of bit-fields are also implemention defined:
- The alignment of bit fields in the storage unit. For example, the bit fields may be allocated from the high end or the low end of the storage unit.
- Whether or not bit-fields can overlap an storage unit boundary. For example, assuming eight bits to a byte, if bit-fields of six and four bits are declared, is each bitfield contained within a byte or are they be split across multiple bytes?
Therefore, it is impossible to write portable code that makes assumptions about the layout of bit-fields structures.
References
- ISO/IEC 9899-1999 Section 6.7.2, "Type specifiers"
- MISRA 04 Rule 3.5