cstructbit-manipulation

Have fields in bit fields got contiguous memory location for its elements? Is this behavior compiler independent?


In a bit field in C, are the memory locations of its elements contiguous? If yes, is this behavior equal for all compilers?

Example:

typedef struct
{
   uint8_t        in_alarm      :1;
   uint8_t        fault         :1;
   uint8_t        overridden    :1;
   uint8_t        out_of_service:1;
}StatusFlag_t;

Will the fields in_alarm, fault etc have contiguous memory locations?


Solution

  • Almost every aspect of bit-field handling is compiler dependent according to the C standard. The chances are that the 4 bits in your structure will be contiguous in a single byte, but it is not guaranteed whether they'll be the most-significant or least-significant 4 bits. If there were more than 8 bits, then the values would cross more than one storage unit (because the base type is uint8_t; note that the C standard does not require a compiler to support the use of uint8_t as the type of a bit-field). Note that bit-field members usually do not have different addresses; you can't take the address of a bit-field element.

    There is no guarantee that different compilers will behave the same across different platforms. There is typically an ABI (application binary interface) which defines the behaviour for a particular O/S, and the compiler will adhere to the ABI for the platform on which it is running. But the C standard does not mandate this behaviour.

    For relevant quotes from the standard, see (amongst other possibilities) How do bit-fields and their alignments work in C programming?