Typedef in C

Typedef in C

C-typedef is a keyword used to provide meaningful names to the already existing variable in C programming. It is used to assign an alternative name to an already existing datatype.

Syntax of Typedef in C

typedef <existing_name> <alias_name>  

Here,existing_name is shown that the name of an already existing data type and alias_name is shown that an alternative name given to it. 

Example of typedef in C

suppose, create a variable of type unsigned int, then if we want to declare multiple variables of this type. 

typedef unsigned int unit;  

Program of typedef in C

#include <stdio.h>  
int main()  
{  
typedef unsigned int unit;  
unit i,j;  
i=20;  
j=30;  
printf("Value of i is :%d",i);  
printf("\nValue of j is :%d",j);  
return 0;  
}  

Output

Value of i is :20 
Value of j is :30

 

Using typedef with Structure

The typedef declaration is used to give a name to user-defined data types. Typedef is used with structures to define a new data type and after that use this data type to define structure variables.

Program of typedef with structure in C

#include <stdio.h>  
typedef struct employee  
{  
char name[25];  
int age;  
}
emp;  
int main()  
{  
stud s;  
printf("Enter the details of emp : ");  
printf("\nEnter the emp name :");  
scanf("%s",&s.name);  
printf("\nEnter the empId :");  
scanf("%d",&s.empId);  
printf("\n emp name is : %s", s.name);  
printf("\n EmpId of the emp is : %d", s.empId);  
return 0;  
}  

Output

Enter the details of emp : 
Enter the emp name : Ram 
Enter the EmpId of emp: 25 
Emp name is : Ram 
EmpId of the emp is : 25 

Using typedef with pointers

Program of typedef with the pointer in C

#include <stdio.h>

int main (){
  typedef int* intptr;

  int MyVar = 20;
  
  intptr p1;
  
  p1 = &MyVar;

  printf("Address stored in p1 variable: %p\n",p1); 
  printf("Value stored in *p1: %i",*p1);
  return 0;
}

Output

Address stored in p1 variable: 0x7ffe2c5a86cc
Value stored in *p1: 20

typedef vs #define

#define is used to define the aliases for different data types similar to typedef.

Typedef is to giving symbolic names to only types where #define is used to define an alias for values and typedef is performed by the compiler where #define statements are processed by the pre-processor.

Program of typedef vs #define

#include <stdio.h>
 
#define TRUE  1
#define FALSE 0
 
int main( ) {
   printf( "TRUE : %d\n", TRUE);
   printf( "FALSE : %d\n", FALSE);

   return 0;
}

Output

TRUE : 1
FALSE : 0

 

 

Read more, goto statement in C

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *