Question

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)?

Was it helpful?

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.

OTHER TIPS

The C standard does not require an implementation to be able to translate a program with more than 1023 members in a struct. C 2011 (N1570) 5.2.4.1 1:

The implementation shall be able to translate and execute at least one program that contains at least one instance of every one of the following limits: … 1023 members in a single structure or union …

An implementation may fail to translate some programs with fewer members, as long as it can translate at least one program with 1023 members (and the other limits). Any implementation of modest quality will be able to handle any reasonable number of members, including bit-fields.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top