Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Self referential structs in c

Tags:

c

struct

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?

like image 870
user2864293 Avatar asked Dec 07 '22 20:12

user2864293


2 Answers

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;
};
like image 85
artm Avatar answered Dec 30 '22 06:12

artm


Self-referential types are valid in C, but in C structs 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.

like image 28
Dai Avatar answered Dec 30 '22 07:12

Dai