Typedef

In C programming language provide some keyword as typedef and some meaningful names to the already existing variable in the C. You can use typedef to give a name to user defined data types and use typedef with structure to define a new data type and then use to define structure variables.

Syntax of typedef

typedef

Lets take an example and see how typedef actually works and look.

typedef unsigned int unit;

The above statement define a term unit for an unsigned int datatype. Now this unit identifier can be used to define unsigned int type variables.

Let’s understand 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 typdef with structures

Consider the below structure declaration :

struct student
{
char name[20];
int age;
};
struct student s1;

But the above typedef can be written as :

typedef struct student
{
char name[20];
int age;
} stud;
stud s1,s2;

From the above declaration we conclude the typedef keyword reduces the length of the code and complexity of data types.

Let’s see the example of typdef the structure declaration

#include <stdio.h>  
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: Neha 
Enter the age of student: 26 
Name of the student is : Neha 
Age of the student is : 26

Using typdef with pointers

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

Syntax to declare a pointer as shown below :

int*ptr;

We can rename the above pointer variable as given below :

typedef int*ptr;

Submit your review
1
2
3
4
5
Submit
     
Cancel

Create your own review

The Technical Funda
Average rating:  
 0 reviews