Declaration rule in struct typedef

I am reading "C programming language" and ran into a typedef struct problem. The code looks like this:

typedef struct tnode *Treeptr; typedef struct tnode { /* the tree node: */ char *word; /* points to the text */ int count; /* number of occurrences */ struct tnode *left; /* left child */ struct tnode *right; /* right child */ } Treenode; 

By the time we write

 typedef struct tnode *Treeptr; 

tnode is still not declared, but we are not getting any compilation error, but when we change the above statement to:

 typedef Treenode *Treeptr; 

We get a compilation error:

 error: parse error before '*' token warning: data definition has no type or storage class 

What makes the difference? Isn't that "struct tnode" like "Treenode"?

+6
source share
3 answers

You cannot use a type before defining it.

When declaring typedef struct tnode { ... } Treenode; the Treenode type Treenode not determined until a semicolon is reached.

The situation with typedef struct tnode *Treeptr; different. This tells the compiler that there is a structure type called struct tnode , and the Treeptr type is an alias for a pointer to struct tnode '. At the end of this declaration, struct tnode is an incomplete type. You can create pointers to incomplete types, but you cannot create variables of an incomplete type (so that you can define Treeptr ptr1; or struct tnode *ptr2; and they are of the same type, but you cannot define struct tnode node; ).

The body of a struct tnode can be written as:

 typedef struct tnode { char *word; int count; Treeptr left; Treeptr right; } Treenode; 

since Treeptr is a well-known alias for the struct tnode * before the structure is defined. You cannot use Treenode *left; , because Treenode not a known alias until the final semicolon is reached (roughly speaking).

+6
source

When you declare TreePtr , you do not implement the structure. This is called a forward declaration. Something like: "here we use it, but later I will explain it better." The implementation should appear later, only once, and this is what you will find in the second typedef .

And TreePtr is not the same as a structure, because TreePtr will actually be a new type that includes the fact of a beeing pointer.

+1
source

String typedef struct tnode *Treeptr; has an implicit direct declaration of the "tnode" structure. It looks like:

 typedef struct tnode Treenode; typedef Treenode *Treeptr; struct tnode { /* the tree node: */ char *word; /* points to the text */ int count; /* number of occurrences */ struct tnode *left; /* left child */ struct tnode *right; /* right child */ }; 
0
source

All Articles