Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should structure names have a typedef?

Tags:

c

struct

typedef

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?

like image 934
Jay Avatar asked Apr 09 '10 07:04

Jay


People also ask

Why do you use typedef in a structure?

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.

Should you use typedef for structs?

In general, a pointer, or a struct that has elements that can reasonably be directly accessed should never be a typedef.

Why are typedef statements useful?

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.

Can typedef and struct have same name?

You can't "typedef a struct", that doesn't mean anything.


1 Answers

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 typedefined, but evidently its easier to read. Also, use of Entry * vs EntryP is totally user-dependent.

like image 60
N 1.1 Avatar answered Oct 19 '22 10:10

N 1.1