Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it legal to initialize multiple overlapping fields in a union's member initializer list?

I have this union:

union Foo
{
    uint32_t u32;
    struct
    {
        uint32_t a : 10;
        uint32_t b : 10;
        uint32_t c : 10;
        uint32_t d : 2;
    };

    Foo() : a(0), b(1), c(2), d(3)
    {
    }
};

We have a tool that analyzes C++ code for potential bugs, and it has a false positive where it thinks that u32 hasn't been initialized when I write this.

I found that VC++ will let me write this member initializer list:

Foo() : u32(0), a(0), b(1), c(2), d(3)

It does shut up the tool, but it looks... mightily dubious. (Edit based on the comments: GCC and Clang won't accept it, so mightily dubious seems justified.)

For structures, member initializers are executed in their order of definition in the structure. Is there something similar for unions that ensures that this doesn't end up zeroed because of u32(0)?

We don't have great pretenses of portability. Right now, this project targets Windows, but it might target iOS and Android in the future. I can pretty much guarantee that it won't show up on strange and exotic platforms though.

Of course, I can just set a, b, c and d in the constructor's body, which sidesteps the whole issue (or I can disable the warning), but it got me curious.

like image 802
zneak Avatar asked Jul 18 '16 23:07

zneak


1 Answers

N4594

12.6.2/§? (Under §9):

[ Note: [...] —end note ] An attempt to initialize more than one non-static data member of a union renders the program ill-formed. [ Note: [...] —end note ]

like image 147
PcAF Avatar answered Sep 19 '22 01:09

PcAF