I'm trying to move some code that was compiling fine as C++ in VS2010 to c (gcc c99) and I'm getting compilation errors. It's a little different than the other self-referential struct questions, because I have 2 user defined types, each of which contains pointers to one another. It seems my forward declartions aren't enough.
struct potato; //forward declare both types
struct tomato;
struct potato
{
potato* pPotato; //error: unknown type name ‘potato’
tomato* pTomato;
};
struct tomato
{
potato* pPotato;
tomato* pTomato;
};
Why does this not work in gcc 99? Why is it ok as C++ code? How should I modify this to get the same behavior as c99?
Alternatively, typedef
them both
typedef struct potato potato; //forward declare both types
typedef struct tomato tomato;
struct potato
{
potato* pPotato;
tomato* pTomato;
};
struct tomato
{
potato* pPotato;
tomato* pTomato;
};
Self-referential types are valid in C, but in C struct
s live in a different namespace to variables/constants and must be prefixed with struct
when their name is used.
Also, avoid Hungarian Notation, in your case the p
prefix.
Try this:
struct potato; //forward declare both types
struct tomato;
struct potato
{
struct potato* potato;
struct tomato* tomato;
};
struct tomato
{
struct potato* potato;
struct tomato* tomato;
};
The traditional way of avoiding having to constantly type struct foo
was to use a typedef
:
typedef struct potato potato;
The definition of struct potato
can be used anonymously and inline:
typedef struct { ... } potato;
I have made a personal observation that use of typedef struct
seems to be in decline and using the "longhand" form of always specifying struct
when used is back in vogue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With