Why should structure names have a typedef?
I have seen source codes always having a typedef for a structure and using the sam开发者_运维知识库e everywhere instead of using the structure name as "struct sname" etc directly?
What is the reason behind this? Are there any advantages in doing this?
Its easier to read Box b;
than struct boxtype b;
typedef struct _entry{
char *name;
int id;
} Entry, *EntryP;
Advantage:
In the above typedef
, both Entry
& EntryP
are defined apart from struct _entry
.
So, EntryP firstentry
can be used in place of struct _entry *firstentry
and is a little simpler to parse in mind.
Note: Its not like structure names should be typedef
ined, but evidently its easier to read. Also, use of Entry *
vs EntryP
is totally user-dependent.
It is an odd quirk in the C language, structure tag names are stored in a different namespace (symbol table). The C++ language got rid of this behavior. The typedef creates an alias for the structure type in the global namespace. So you don't have to type "struct" before the structure name.
Not sure what Ritchie was smoking when he defined this behavior. I'm guessing at some kind of problem with the parser in an early version of the compiler.
I like to do this in C:
// in a "public" header file
typedef struct Example Example;
// in a "private" header or a source file
struct Example { ... };
Like this, I have Example
as an opaque type (i.e., I can only pass pointers to it about) throughout my code, except for the code that implements its operations, which can see what it is really defined as. (You could use a separate name for the opaque type but there's no real advantage to that.)
Its just for the code readability. typedefs are just to give new name for the data type. Instead of giving int every where you can name it the way you want and wherever you use int you can just replace it by the new name you have given. Same thing applies for structures also.
It's a form of information hiding and useful when creating opaque types. See this SO link for a slightly longer answer.
A non-typedefed struct name in C requires "struct" to be prepended everywhere the type name is used, so most people use typedef to create a new name for the type that does not need to have the struct keyword prepended all the time.
The reasons for doing this are code readability, reduced typing, and probably clarity as well, but typedefs can actually obscure information about pointer types.
In all honesty the need to typedef to create new names for structs is a relic, and it's a shame that C99 didn't follow C++'s lead and remove it.
I actually don't use typedef for structs.
Why?
Because I would use some convention such a s_
prefix anyway, to easily see what kind of variable I'm looking at.
Since I use a lot of abstract data types, I guess it would be a good idea to use a typedef, so that the user really uses it as an opaque type. But in practice I always use a struct in the implementation anyway.
精彩评论