[cfe-dev] question about initializing multiple members of unions

Philip R listmail at philipreames.com
Tue Sep 17 08:03:30 PDT 2013


On 9/17/13 6:36 AM, Matthew Curtis wrote:
> On 9/16/2013 1:05 PM, Richard Smith wrote:
> > On Mon, Sep 16, 2013 at 7:11 AM, Matthew Curtis 
> <mcurtis at codeaurora.org> wrote:
> >
> >     Richard, Doug,
> >
> >     Do either of you have an recommendation here?
> >
> >     Eli recommends GCC's behavior, while Philip Reames and Gao would 
> both prefer the alternate behavior below (same as a series of 
> assignments).
> >
> > Can you explain how treating the designated initializers as a 
> sequence of assignments could give the object the value {0, 1, 2, 3}?
>
> Given the following program :
>
>     #include <stdio.h>
>
>     typedef union {
>       struct {
>         int zero;
>         int one;
>         int two;
>         int three;
>       } a;
>       int b[4];
>     } my_agg_t;
>
>     // set value using initializer
>     my_agg_t X = {
>       .b[0] = 0,
>       .a.one = 1,
>       .b[2] = 2,
>       .a.three = 3,
>     };
>
>     int main(int argc, char *argv[])
>     {
>
>       // set value using series of assignments
>       my_agg_t Y;
>       Y.b[0] = 0;
>       Y.a.one = 1;
>       Y.b[2] = 2;
>       Y.a.three = 3;
>
>       printf("X:%d,%d,%d,%d\n", X.a.zero, X.a.one, X.a.two, X.a.three);
>       printf("Y:%d,%d,%d,%d\n", Y.a.zero, Y.a.one, Y.a.two, Y.a.three);
>     }
>
> GCC Produces:
>
>     X:0,0,0,3
>     Y:0,1,2,3
>
> I believe Goa and Philip Reames are arguing that it seems very 
> unintuitive that while the source code for setting X and setting Y 
> look very similar they produce very different results.
You summarized my argument well.  Thanks.
>
> > I'm reasonably convinced that this is a hole in the C standard -- it 
> doesn't specify what to do in this case -- and Eli's approach seems 
> completely reasonable to me. Plus it has the benefit of > being 
> compatible with at least two other major compilers (g++ and EDG), and 
> doesn't require us to invent a new representation for initializer lists.
>
> On 9/16/2013 5:28 PM, Richard Smith wrote:
> > I still think Eli's approach is the right one here.
>
> I agree.
>
> Does this require further discussion or can I submit a patch that 
> implements this behavior?
No further discussion needed.  I am still concerned about the possible 
confusion, but agree the compatibility argument is a strong one as 
well.  I will defer to the your choice.

Philip




More information about the cfe-dev mailing list