I have seen source codes always having a typedef for a structure and using the same 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?
The C language contains the typedef keyword to allow users to provide alternative names for the primitive (e.g., int) and user-defined (e.g struct) data types. Remember, this keyword adds a new name for some existing data type but does not create a new type.
In general, a pointer, or a struct that has elements that can reasonably be directly accessed should never be a typedef.
The typedef is an advance feature in C language which allows us to create an alias or new name for an existing type or user defined type.
You can't "typedef a struct", that doesn't mean anything.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With