I\'m trying to typedef a struct which contains a pointer to another of the same type.
Thats what I thought would be the best version:>
Your first variant is correct. Your second variant doesn't do what it appears to do.
In C, it's valid to forward-declare a struct type anywhere, even in the middle of declaring something else. (The scoping rules for such declarations-in-passing are confusing to the point where I'm not going to try to explain them -- suffice to say that you should avoid doing so.) That is why you don't get an error on the second construct. But what it means to the compiler is this:
struct _Anonymous_1 // name not actually accessible to code
{
char value;
struct Element *next;
};
typedef struct _Anonymous_1 Element;
After this code, the type "struct Element" is completely unrelated to the type "Element", and has not been fully declared. If you were to attempt to use that type, e.g. in
char cadr(Element *cons)
{
return cons->next->value;
}
the compiler would not be happy:
test.c: In function ‘cadr’:
test.c:9:22: error: dereferencing pointer to incomplete type
An alternative to your first variant, that lets you use 'Element' instead of 'struct Element' everywhere, including inside the definition of the type, is
typedef struct Element Element;
struct Element
{
char value;
Element *next;
};
But in C there is no way to avoid having to manually make sure that "struct Element" is the same thing as "Element". If you don't want to have to deal with it, C++ is waiting for you over there ⟶