There is a reserved keyword typedef used in C programming language to give an alternative meaningful name to existing data type. This keyword can be used with both primitive and user defined data types although it is preferred to be used with user defined data types.

 

SYNTAX

The syntax for using typedef in C program is given below:

typedef existing name <alias name>;

The typedef keyword should be written exactly the way it is shown in the above syntax. Typedef or type def will be considered invalid.

The existing name is the name of already defined variable.
Alias name is the new name given to the existing variable.

Use of typedef

To create a variable of data type signed int we can use typedef keyword.
typedef signed int num;

Now you can defined variable of signed int type without using the statement signed int multiple times.
We have used the typedef keyword to declare the num variable of type signed int, so now we can create variables of signed int type using the following statements:

num x;
num y;
num z;

Instead of writing –

signed int x;
signed int y;
signed int z;

Hence, typedef provides a shortcut of defining variables by giving another names to already existing data types.

 

Example :

#include <stdio.h>
{
typedef signed int num;
num x,y;
x = 20;
y = 10;
printf ( “ Value of x is : % d \n ”, x);
printf ( “ Value of y is : % d \n ” , y);
return 0;
}

Result

Value of x is : 20
Value of y is : 10

 

Use of typedef in structure declaration

 

struct employee
{
char name[20];
int gender;
};
struct employee p1;

In the above code, we have defined the variable of employee type using the following statement
struct employee p1;

You can avoid this statement( which is quite long) by using the typedef keyword to create the variable of type employee.

struct employee
{
char name[20];
int gender;
} ;
typedef struct employee emp;
emp e1, e2; 

In the above code, we have declared the variable emp of type struct employee. And now we can use the emp variable in program to create the variables of type struct employee.

Leave a Reply

Your email address will not be published. Required fields are marked *