Home » Typedef in C

typedef in C

The typedef is a keyword used in C programming to provide some meaningful names to the already existing variable in the C program. It behaves similarly as we define the alias for the commands. In short, we can say that this keyword is used to redefine the name of an already existing variable.

Syntax of typedef

In the above syntax, ‘existing_name’ is the name of an already existing variable while ‘alias name’ is another name given to the existing variable.

For example, suppose we want to create a variable of type unsigned int, then it becomes a tedious task if we want to declare multiple variables of this type. To overcome the problem, we use a typedef keyword.

In the above statements, we have declared the unit variable of type unsigned int by using a typedef keyword.

Now, we can create the variables of type unsigned int by writing the following statement:

instead of writing:

Till now, we have observed that the typedef keyword provides a nice shortcut by providing an alternative name for an already existing variable. This keyword is useful when we are dealing with the long data type especially, structure declarations.

Let’s understand through a simple example.

Output

Value of i is :10   Value of j is :20   

Using typedef with structures

Consider the below structure declaration:

In the above structure declaration, we have created the variable of student type by writing the following statement:

The above statement shows the creation of a variable, i.e., s1, but the statement is quite big. To avoid such a big statement, we use the typedef keyword to create the variable of type student.

In the above statement, we have declared the variable stud of type struct student. Now, we can use the stud variable in a program to create the variables of type struct student.

The above typedef can be written as:

From the above declarations, we conclude that typedef keyword reduces the length of the code and complexity of data types. It also helps in understanding the program.

Let’s see another example where we typedef the structure declaration.

Output

Enter the details of student s1:   Enter the name of the student: Peter   Enter the age of student: 28   Name of the student is : Peter   Age of the student is : 28   

Using typedef with pointers

We can also provide another name or alias name to the pointer variables with the help of the typedef.

For example, we normally declare a pointer, as shown below:

We can rename the above pointer variable as given below:

In the above statement, we have declared the variable of type int*. Now, we can create the variable of type int* by simply using the ‘ptr’ variable as shown in the below statement:

In the above statement, p1 and p2 are the variables of type ‘ptr’.


You may also like