Minimal code example:
struct B {
union U {
struct S {} s;
int i = 100;
}
u;
};
Now if we declare a B obj; then the obj.u.i is assigned a garbage value instead of 100. See the demo here. (The garbage value differs based on optimization flags etc.).
Is the "In class initialization" feature supposed to work with unions.
- If yes, then what is the correct syntax? Or is this a g++ bug?
- If not then what
int i = 100;does?
This looks like a GCC bug. The standard says (9.5p2):
Otherwise, the rules are the same as for a regular class.
EDIT: In addition, 12.6.2p8:
Presumably the implicitly defined default constructor counts here. The
imember meets the criteria in the first bullet point, so it's initialized like it were a regular class member. Thesmember matches the second bullet point, so it's left uninitialized.