Search code examples
cstructbit-fields

Is there a maximum number of bit field entries in a C structure?


The question is more specifically this one: How many bit-field entries can I add in a structure?

For example:

struct SMyStruct
{
   unsigned int m_data1 : 3;
   unsigned int m_data2 : 1;
   unsigned int m_data3 : 7;
   // ...
   unsigned long long m_datan : 42;
};

May the total of bits exceed 32 or 64 (or whatever is the system architecture)?


Solution

  • It's not limited, what is important is that the number of bit-fields can not be grater than the number of bit's of the data type, for example:

    typedef struct _Structure {
      int field1:32;  // OK
      int field2:40;  // Error, int is 32 bit size
      char field3:4;  // OK
      char field4:9;  // Error, char is 8 bit size
    } Structure;
    

    The size of data type, the number of bit-fields, and endianness are hardware/compiler depends.