4

Is the order of members in a) in a struct b) in a bitfield guaruanteed? In other words, given a certain member of a struct or a bitfield, am I guaranteed that its offset from the beginning of the struct/bitfield will be no less than the sum of the sizes of the members that preceded it?

To give an example:

struct S{
   char a[N];
   unsigned b : M;
   char c : O;  
};

Will the offset of c be at least sizeof(a)+sizeof(b)?

Petr Skocik
  • 58,047
  • 6
  • 95
  • 142
  • No. There is also alignment involved. – Pyjong Feb 26 '16 at 11:20
  • @Pyjong that's why it says "no less" – Petr Skocik Feb 26 '16 at 11:20
  • @Mat That's an awful "duplicate". Bit-fields are not structs! While structs guarantee an order of allocation, bit-fields do not guarantee where their bits end up. [Here](http://stackoverflow.com/questions/6043483/why-bit-endianness-is-an-issue-in-bitfields) is a better duplicate. – Lundin Feb 26 '16 at 12:46

1 Answers1

3

Yes.

C++ standard:

Nonstatic data members of a (non-union) class declared without an intervening access-specifier are allocated so that later members have higher addresses within a class object.

Rob L
  • 2,351
  • 13
  • 23