Is it possible to use array of bit fields?

msc picture msc · Jan 29, 2017 · Viewed 16.3k times · Source

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

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

Answer

haccks picture haccks · Jan 29, 2017

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];