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

Philip R listmail at philipreames.com
Thu Sep 12 15:35:05 PDT 2013


On 9/12/13 2:04 PM, Matthew Curtis wrote:
> On 9/11/2013 2:30 PM, Eli Friedman wrote:
>> On Wed, Sep 11, 2013 at 6:10 AM, Matthew Curtis 
>> <mcurtis at codeaurora.org <mailto:mcurtis at codeaurora.org>> wrote:
>>
>>     I'm investigating an assert in clang compiling the following code:
>>
>>       typedef union {
>>         struct {
>>           int zero;
>>           int one;
>>           int two;
>>           int three;
>>         } a;
>>         int b[4];
>>       } my_agg_t;
>>
>>       my_agg_t agg_instance =
>>       {
>>         .b[0] = 0,
>>         .a.one = 1,
>>         .b[2] = 2,
>>         .a.three = 3,
>>       };
>>
>>     I'm a little uncertain as to what this *should* do.
>>
>> This is also http://llvm.org/bugs/show_bug.cgi?id=16644 .
>>
>> I would say we should either use gcc's interpretation or reject it.
>>
>> -Eli
>
> Sounds reasonable. Unless someone has a dissenting opinion, I'll look 
> at fixing this by making clang consistent with gcc.
>
> Thanks,
> Matthew Curtis
I would argue somewhat strongly against adopting gcc's interpretation.  
I'm not going to get into the specification debate - I'll leave that to 
others who are more knowledgeable - but the gcc behavior is highly 
unintuitive.

The closest code analogy I could think of would be this:
my_agg_t agg;
(agg.b[0] = 0, agg.a.one = 1, agg.b[2] = 2, agg.a.three = 3);
printf("%d, %d, %d, %d\n", agg.a.zero, agg.a.one, agg.a.two, agg.a.three);

I tried this code with both clang and gcc at various levels of 
optimization and got the same result: "0, 1, 2, 3".  I expect getting 
any other results would be considered unintuitive at the least by most 
programmers.

Given that these code fragments are obvious candidates for manual 
"refactoring" moving from c++03 to c++11, this unintuitive difference 
seems particularly problematic.

Yours,
Philip Reames


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/cfe-dev/attachments/20130912/ef80bf0d/attachment.html>


More information about the cfe-dev mailing list