typedef in C Language
Categories: C language
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
typedef <existing_name> <alias_name>
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.
typedef unsigned int unit;
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:
unit a, b;
instead of writing:
unsigned int a, b;
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.
#include <stdio.h>
int main()
{
typedef unsigned int unit;
unit i,j;
i=10;
j=20;
printf("Value of i is :%d",i);
printf("\nValue of j is :%d",j);
return 0;
}
Output
Value of i is :10
Value of j is :20
Using typedef with structures
Consider the below structure declaration:
struct student
{
char name[20];
int age;
};
struct student s1;
In the above structure declaration, we have created the variable of student type by writing the following statement:
struct student s1;