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
typedef
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;
Now, we can create the variables of type unsigned int by writing the following statement:
unit a, b;
unsigned int a, b;
Let's understand through a simple example.
#include
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;
struct student s1;
struct student
{
char name[20];
int age;
};
typedef struct student stud;
stud s1, s2;
typedef struct student
{
char name[20];
int age;
} stud;
stud s1,s2;
#include
typedef struct student
{
char name[20];
int age;
}stud;
int main()
{
stud s1;
printf("Enter the details of student s1: ");
printf("nEnter the name of the student:");
scanf("%s",&s1.name);
printf("nEnter the age of student:");
scanf("%d",&s1.age);
printf("n Name of the student is : %s", s1.name);
printf("n Age of the student is : %d", s1.age);
return 0;
}
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:
int* ptr;
typedef int* ptr;
ptr p1, p2 ;