Typedef in C


Typedef is a keyword in C programming language which is used to assign different names to existing data types. The typedef keyword is mostly used with the built in data types of C programming language. The following is the syntax of using the typedef keyword in C programming language:

typedef existing-name alias-name;

In the above statement existing-name is the actual name of the data type and alias-name will be the name that will be assigned by the user to the existing data type. Consider the following example in which we are assigning a new name to existing data type that is unsigned long:

typedef unsigned to ulong;

Now ulong is the new name of the data type unsigned long which can be used to declare variables. Consider the following example:

ulong x, y;


Application of typedef:

We can also use the typedef keyword to assign a name to user defined data types. For example we can assign name to struct. Consider the following example in which we have done this:

CODE:

typedef struct

{

  type member1;

  type member2;

  type member3;

} type_name ;

In the above example type_name is used to represent the definition of the structure and this can be used to declare a variable of structure type.


Example of structure definition using typedef:

Consider the following example in which we have used the typedef keyword:

CODE:

# include <stdio. h>

# include <conio. h>

# include <string. h>

typedef struct student

{

 char name [50];

 int fee;

} stu;

void main ( )

{

 stu s1;

 printf (“\nEnter Student record\n”);

 printf (“\nStudent name\t”);

 scanf (“%s”, s1. name);

 printf (“\nEnter Student fee \t”);

 scanf (“%d”, &s1. fee);

 printf (“\nStudent name is %s”,s1.name);

 printf (“\nfee is %d”, s1. salary);

 getch ();

}


typedef and pointers:

We can also use the typedef keyword in C programming language to give an alias name to pointers. The typedef keyword is useful with pointers when we are declaring pointers. Consider the following example:

int * a, b;

In this statement the variable ‘a’ is actually declared as pointer of integer data type and the variable b is a simple variable of integer data type. We use the typedef keyword to declare more than one pointer in single statement. Consider the following line of code:

typedef int * IntPtr;

IntPtr a, b, c;

Now we have pointer IntPtr of integer data type and we used the typedef keyword. In this way we can use the pointer IntPtr to declare any number of pointers of integer data type in one statement.