Given the following code:
typedef struct elementT {
int data;
struct elementT *next;
} element;
Why is it necessary to do struct elementT *next and I can’t do element *next inside the struct declaration itself? Is it because it is not declared yet?
The
typedefonly takes place after thestructhas been defined. Consider the following code; the syntax is invalid, but it hopes it shows the order/precedence of things:I.e., the
struct{...}is an "expression" that denotes a type. Thetypedefoperates on that type by giving it a name.By contrast,
works because of two special rules of C:
struct <name>not only defines a type, but gives it astructtag as well, and that tag is immediately visible inside the rest of thestructdeclaration (for the obvious reason: linked lists, trees, etc. would be very painful to implement without these rules).