I am writing a tagged union in C, the definition is as follows:
struct uuid_0000000000061d0c {
long _0;
union {
struct {void* _1;};
struct {char* _1001; char* _1002;};
struct {char* _2001;};
struct {};
};
};
There are four anonymous cases in a tagged union. My question is when I initialize this with the "large" two field case I end up with a warning "warning: excess elements in struct initializer".
struct uuid_0000000000061d0c an_instance = { 1, "a", "b" };
Following my intuition I successfully restructured the original type definition to avoid the error. Basically, moving the anonymous struct with the largest number of fields to the start of the union fixes this warning.
struct uuid_0000000000061d0c {
long _0;
union {
struct {char* _1001; char* _1002;};
struct {void* _1;};
struct {char* _2001;};
struct {};
};
};
Is this a bug with the warning or am I misunderstanding the intent of the warning?
There are 3 non-conformance issues here:
struct {};
is invalid C syntax. Structs must have members.
struct uuid_0000000000061d0c an_instance = { 1, "a", "b" };
attempts to initialize 3 items in a struct which only has 2 items. GNU non-standard extensions can in some situations let through code with more initializers than elements, but that doesn't make the code valid C.
If you wish to initialize a particular union
member the best way is to use designated initializers. If you don't use them, the first union member will get initialized. Why the fix "worked". Instead you should write something like:
{ ._0 = 1, ._1001 = "a", ._1002 = "b" };
Structs are usually declared at file scope so that multiple functions can access them. If that's what you are planning to do here, the members (or tag names) cannot start with _
since that's reserved for the compiler at file scope.