Packed structure size with bit field aggregation less than 8 bits in C

Is it possible for C to get the size of the following structure: 2?

#include <stdio.h> struct union_struct { char foo; char bar : 2; union { char foobar1 : 6; char foobar2 : 6; }; }; int main(void) { printf("size of union struct: %d\n", sizeof(struct union_struct)); return 0; } 

compiled using gcc:

size of union struct: 3

+4
c sizeof bit-fields packed
source share
1 answer

If you rely on the behavior defined by the implementation, then yes, but you should streamline it a bit:

 #ifdef UNNAMED_BITFIELDS_ARE_WELL_DEFINED #define ANON #else #define ANON3(X) anonymous__## X ##__ #define ANON2(X) ANON3(X) #define ANON ANON2(__LINE__) #endif struct union_struct { char foo; union { struct { char bar : 2; char ANON : 6; }; struct { char ANON : 2; char foobar1 : 6; }; struct { char ANON : 2; char foobar2 : 6; }; }; }; 

The first byte is foo , the second is an anonymous union. Then an anonymous union has 3 single-byte anonymous structures. Each structure (optionally) uses unnamed bit fields to allow foobar1 and foobar2 represent the same 6 bits that follow bar .

From my understanding of the C.11 standard, the above code is correct if UNNAMED_BITFIELDS_ARE_WELL_DEFINED defined. However, there seems to be a discussion about whether unnamed bit fields have clearly defined semantics (see Comments below). If the unwritten bit fields do not have well-defined semantics, then the above code can expand each ANON macro into a name for the bit field.

However, the C.11 standard only defines bit fields in _Bool , int and unsigned , while using any other type for the bit field is an implementation (C.11 & sect; 6.7.2.1 and clause 5).

+5
source share

All Articles