Search code examples
cunionsbit-fields

Is it possible and correct to form union from bit-field in C?


I have the following union and it works correct:

#pragma pack(1)
...
union
{
    uint8_t opcode;
    struct
    {
        uint8_t z : 3;
        uint8_t y : 3;
        uint8_t x : 2;
    };
}opcode;    

The size of the union is exactly one byte, according to

printf ("%zu\n", sizeof opcode);  

The problem takes place when I try to make a union from the bit-field there:

union
{
    uint8_t opcode;
    struct
    {
        uint8_t z : 3;
        union
        {
            uint8_t y : 3;
            struct
            {
                uint8_t p : 2;
                uint8_t q : 1;
            };
        }y;
        uint8_t x : 2;
    };
}opcode;    

The result of

printf ("%zu\n", sizeof opcode);  

is 3 bytes. Of course I can workaround this with macros but it is it possible at all?


Solution

  • No, it isn't possible to have structs that are fractions of a byte big.

    Rationale:

    It must be possible to make a pointer to a struct, and the smallest adressable unit is 1 byte.

    Note: This limitation exists in all compilers that I know. I don't know whether it is actually mandated by the C standard.