1

Similar to c union and bitfields but in C++ and including access to initial sequence

Similar to Union common initial sequence with primitive but using bitfields

What I want to do is this:

struct A
{
   short common : 1;
   short a1: 5;
   short a2: 8;
};

struct B
{
   short common : 1;
   short b1: 3;
   short b2: 4;
   short b3: 6;
};

union C
{
    A a;
    B b;
};

Then use it as follows:

short foo(C data)
{
   if (data.a.common)
   {
       return data.a.a1*data.a.a2;
   }
   return data.b.b1*data.b.b2*data.b.b3;
}

The issue seems to be that if data.a.common is false, the code will have accessed data set as a B via a member of A

There seems to be language in the standard about unions and similar initial sequences, but not sure common as a bitfield would count

9.5.1 it is permitted to inspect the common initial sequence of any of standard-layout struct members;

Any clarification would be appreciated

Glenn Teitelbaum
  • 10,108
  • 3
  • 36
  • 80
  • The size of the union is always the size of its biggest element. in your case it would be the size of B which would be 8 bytes. That means all members of A and B are safe to access, but if you have not set it to a meaningful value, it might produce random result. Some compilers initialize everything with 0, but some don't. Even then that functionality might be turned off by optimization settings. It would help if you could tell us what you are trying to achieve. – Sam Oct 11 '19 at 14:49
  • @Sam A,B and C are sizeof(short)==2bytes==16 bits with a few wasted – Glenn Teitelbaum Oct 11 '19 at 16:39

1 Answers1

1

By the definition of common initial sequence:

The common initial sequence of two standard-layout struct ([class.prop]) types is the longest sequence of non-static data members and bit-fields in declaration order, starting with the first such entity in each of the structs, such that corresponding entities have layout-compatible types, either both entities are declared with the no_­unique_­address attribute ([dcl.attr.nouniqueaddr]) or neither is, and either both entities are bit-fields with the same width or neither is a bit-field.

the common initial sequence of struct A and struct B consists of the first bit-field common.

Language Lawyer
  • 3,378
  • 1
  • 12
  • 29