C typedef

typedef is a keyword in C programming used to assign alternative name (allias name) to the existing type.

There are two reasons for using typedef. They are

  1. It provides a means to make program more portable i.e instead of changing the type appears throughout the program’s source file,only single typedef need to be changed.
  2. typedef can make a complex declaration easier to understand.

Note :  typedef doesn’t introduce a new datatype but it just provide a new name for a type.

Syntax of C typedef

The syntax of typedef in C is

typedef <type> identifier

where

  • type – existing datatype
  • identifier – new name to the datatype

typedef can be used with struct, union, enum, function pointers.

ADVERTISEMENT

Example

typedef int MARK;

here, MARK is the new name for int. To declare variables using the new datatype name, precede the variable name with new datatype name.

MARK s1,s2;

Instead of declaring like int s1,s2 ,we are declaring with MARK s1,s2.

Example

Consider the structure below.

struct student {
    char name[20];
    int mark[3];
};

To create a variable for the above structure, the syntax would be like :

struct student stud1;

we can make the construct shorter with more meaningful name for types by using typedef.

typedef struct student {
    char name[20];
    int mark[3];
};

For the above student struct, variable creation would be :

student stud1;

Example – C typedef – Creating variables

typedef struct student {
    char name[20];
    int mark[3];
}STUD;

Here the new name of datatype is STUD, we can create variables as

STUD s1,s2;

Example – C typedef with enum

Using typedef with enum is given below.

typedef enum { Saturday,Sunday Monday,tuesday} WEEK ;
WEEK day;

enum without typedef is given below.

enum WEEK{Saturday,Sunday,Monday,Tuesday};
enum WEEK day;

Example – C typedef with union

Using typedef with union is given below.

typedef union account_name; {
	char  name[20];
	char email[20];
}

typedef struct account {
	account_name name;
	char password[20];
};

account user1, user2;

Through this way we can use typedef with many concepts for portability and for easy understanding.

Conclusion

In this C Tutorial – we learned about typedef in C, with the help of syntax and examples.