The difference between these two typedef declarations
typedef struct tnode TNODE;
struct tnode {
int count;
TNODE *left, *right;
};
TNODE s, *sp;
and
typedef struct {
int a;
int b;
} ab_t;
.
is that in the second case you declared an unnamed structure. It means that within the structure you can not refer to itself. For example you can not write
typede struct {
int count;
TNODE *left, *right;
} TNODE;
because the name TNODE
used in this member declaration
TNODE *left, *right;
is not declared yet.
But you can refer to the structure if the structure tag will have a name like
struct tnode {
int count;
struct tnode *left, *right;
};
because the name struct tnode was already declared.
Another difference is that to declare a pointer to a structure there is no need to have a complete definition of the structure. That is you may write
typedef struct tnode TNODE;
TNODE *sp;
struct tnode {
int count;
TNODE *left, *right;
};
Pay attention to that you may write a typedef declaration also the following way
struct tnode {
int count;
struct tnode *left, *right;
} typedef TNODE;
typedef struct tnode { int count; struct tnode *left; struct tnode *right; } TNODE;
which uses the tagged structure name inside the structure because the typedef name isn't available until after the semicolon at the end. For most practical purposes, this is equivalent to the first example. – Giovannatypedef struct tagname tagname;
. The body of the structure can appear between the two occurrences oftagname
. (C++ provides essentially this service automatically; after declaringstruct tag
, the plain nametag
is available for use too.) – Giovannatypedef
is way overused. It provides a convenience -- occasionally a considerable one -- but it is usually possible to write clean, clear C code without ever declaring a typedef. Indeed, I would go so far as to argue that declaring and using typedefs is usually more obfuscatory than not. When that year comes that I get around to writing my C book,typedef
will go into one of the "advanced topics" chapters. – CyrilcyrillFILE
are nice abstract types. From a user standpoint, it makes no difference if it is astruct
,union
,int
, etc. Withouttypedef
, users would lose the ability to form similar abstract types. – Tierza