I have a quick question..is there any difference in these:
struct myinnerstruct
{
int x;
};
struct mystruct
{
struct myinnerstruct m;
int y;
};
AND THIS
struct mystruct
{
int x;
struct myinnerstruct
{
int y;
};
struct myinnerstruct m;
};
These both work as far as I can tell, but I’m wondering if there’s a reason to pick one or the other. Thanks
The difference is that the second one is invalid.
The stuff between the
{and}in a struct declaration is a sequence of member declarations. Youris a type declaration; it doesn’t declare a member of the enclosing struct, so it’s illegal in that context.
What you can do is this:
The declaration of
mis a member declaration, so it’s ok; it also declares the typestruct myinnerstruct. But in my opinion, it’s poor style. The typestruct myinnerstructremains visible after the declaration ofstruct mystructis completed; see below for the explanation.If you really want a struct within a struct like that, and you’re not going to use
struct myinnerstructanywhere else, you could leave it without a tag:But then you might as well declare
yas a member ofstruct mystruct.If you want
struct innerstructto be a named type, just declare it separately, as you did in your first example.Here’s the explanation of why
struct innerstructremains visible.The C99 standard (large PDF), section 6.2.1 paragraph 2, says:
The C90 and C11 standards have essentially the same wording.
The
{braces}in a struct declaration do not define a block, nor do they define any of the other possible kinds of scope, so anything declared between the braces is not scoped to that region; it must be scoped to some surrounding context. It happens that the syntax lets you declarestruct myinnerstructinside another struct definition — but only if it’s part of a member definition. I think this is allowed only because the designers of the language didn’t go to any extra effort to disallow it; it’s just a side effect of other rules. You can do it, but I don’t recommend it.