c++carraysstructbit-fields

Is it possible to use array of bit fields?


I am curious to know, Is it possible to use array of bit fields? Like:

struct st
{
  unsigned int i[5]: 4;
}; 

Solution

  • No, you can't. Bit field can only be used with integral type variables.

    C11-§6.7.2.1/5

    A bit-field shall have a type that is a qualified or unqualified version of _Bool, signed int, unsigned int, or some other implementation-defined type.

    Alternatively you can do this

    struct st
    {
        unsigned int i: 4;  
    } arr_st[5]; 
    

    but its size will be 5 times the size of a struct (as mentioned in comment by @Jonathan Leffler) having 5 members each with bit field 4. So, it doesn't make much sense here.

    More closely you can do this

    struct st
    {
        uint8_t i: 4;   // Will take only a byte
    } arr_st[5];