Reputation: 29
I'm reading some c codes and find that some struct contains a union name without a variable name, just as the following example:
typedef union Lock Lock;
union Lock{
uint32 key;
};
struct Test{
Lock;
uint32 name1;
};
What does the Lock inside Test mean? PS. the type uint32 has already been defined before the two declaration.
Upvotes: 2
Views: 301
Reputation: 62797
So, with typedef added, gcc produces warning:
main.c:8:9: warning: declaration does not declare anything [enabled by default]
Also, simple sizeof
reveals that these have same size:
struct Test{
Lock;
uint32 name1;
};
struct Test2{
uint32 name1;
};
I don't think in C there is any scenario, where this can mean anything useful. Maybe it is a confused attempt at forward declaration.
Upvotes: 0
Reputation: 16726
If you can compile your code, I guess you are using an old compiler or a compiler which still supports implicit int. This would mean that the compiler interprets your code as
struct Test{
int Lock;
uint32 name1;
}
Please see also Why does/did C allow implicit function and typeless variable declarations?
Upvotes: 0
Reputation: 182629
What you posted isn't valid C. As far as the language is concerned, Lock
and union Lock
are completely different things and that's that.
If however you were to say union Lock
inside the struct it would compile but wouldn't do anything: it would be just a superfluous declaration declaring nothing.
There's some speculation that adding a union Lock
or Lock
at the beginning of the struct does something. A quick check should prove that false:
printf("%zu\n", offsetof(struct Test, name1)); /* Will print 0. */
Upvotes: 0