Reputation: 1369
I could not come to the reason why i m getting compilation error to this code?Would be great help if someone clarified it.
int main()
{
struct xx
{
int x;
struct yy
{
int z;
struct xx *p;
};
struct yy *q;
};
}
Upvotes: 0
Views: 173
Reputation: 73443
You are missing ;
at the statement struct xx* p
.
struct xx *p;
} *q
Upvotes: 0
Reputation: 320481
In C language you are not allowed to declare struct
types inside other struct
types without immediately introducing a data field. I.e. struct declaration and data field declaration should be done in one step (as one declaration). You violated that rule: your struct yy
definition just sits inside struct xx
definition for no reason whatsoever.
Either pull the struct yy
definition outside of struct xx
, or make sure that struct yy
definition immediately declares a field of xx
.
For example, this implements the same intent, but does it correctly
struct xx
{
int x;
struct yy
{
int z;
struct xx *p;
} *q; // `struct yy` definition is immediately used to declare field `q`
};
However, usually in C language there's no reason to create nested struct definitions. It is usually a better idea to define structs at the same level, without any nesting
struct yy
{
int z;
struct xx *p;
};
struct xx
{
int x;
struct yy *q;
};
Why didn't you do it that way from the beginning? What was the point of defining these structs in "nested" fasion?
Upvotes: 2
Reputation:
The structure yy is nested within structure xx. Hence, the elements are of yy are to be accessed through the instance of structure xx, which needs an instance of yy to be known. If the instance is created after defining the structure the compiler will not know about the instance relative to xx. Hence for nested structure yy you have to declare member.
Upvotes: 0