------- Comment #10 from runipg at broadcom dot com  2010-09-03 19:19 -------
Subject: Re:  Bug with anonymous unions and bit-fields

Your suggestion works:

struct bfc {
      union {
            struct {
                  unsigned int a : 1,
                     b : 4;
            };
            unsigned int data;
      };
};

void
testc()
{
   cout << __func__ << endl;

   bfc bf0;
   bf0.data = 0;

   cout << "bf0.data=" << hex << bf0.data << endl;
   cout << "bf0.a=" << bf0.a << endl;
   cout << "bf0.b=" << bf0.b << endl;

   bf0.a = 1;

   cout << "bf0.data=" << hex << bf0.data << endl;
   cout << "bf0.a=" << bf0.a << endl;
   cout << "bf0.b=" << hex << bf0.b << endl;

   bf0.b = 1;

   cout << "bf0.data=" << hex << bf0.data << endl;
   cout << "bf0.a=" << bf0.a << endl;
   cout << "bf0.b=" << hex << bf0.b << endl;
}

Output is ....

testc
bf0.data=0
bf0.a=0
bf0.b=0
bf0.data=1
bf0.a=1
bf0.b=0
bf0.data=3
bf0.a=1
bf0.b=1
-----------------------------------------------------------------------------------

I guess the fundamental issue which confused me was:

struct bfa {
      union {
            unsigned int a : 1,
               b : 4;
            unsigned int data;
      };
};

that it appeared to be a union of 2 integers (one bit-field) rather than 
the implementation version where the union is of 3 integers 
(two-bitfields).  If the standard does not say anything specific about 
it, then I guess the compiler is free to do whatever it wants.

In fact, I tried a slight variation on bfa, where I tried to force 
alignment on the first integer packing.

struct bfd {
      union {
            unsigned int a : 1,
               b : 4,
                   : 0;   //force alignment
            unsigned int data;
      };
};

However this gives the same result as bfa.

So I guess semantically it is very confusing to a user. Perhaps this 
part of the language should be tightened.

Thanks Paolo!

-Runip

paolo dot carlini at oracle dot com wrote:
> ------- Comment #8 from paolo dot carlini at oracle dot com  2010-09-03 10:46 
> -------
> If you look at the actual Standard, both alignment and allocation of 
> bit-fields
> are implementation defined. Thus, as far as I can see, at best we are talking
> about non-portable implementation defined behavior. If you want my advice, try
> to stay away from those tricks, with and without anonymous struct.
>
>
>   


-- 


http://gcc.gnu.org/bugzilla/show_bug.cgi?id=45510

Reply via email to