What is typedef in C?

typedef is a keyword that is used to rename the existing primitive and user-defined datatypes. Note that it doesn’t create a new type.

Syntax

typedef <data_type> <new_name>;

How to use typedef in c programming?

We can use typedef in 3 different ways. They are as follows.

Typedef with primitive datatypes

In the above statement, typedef is a keyword, data_type is existing primitive or user-defined datatype like int, float,.. and new_name is an alias to the existing one.

Example is shown below:

// C program to illustrate typedef
#include<stdio.h>
int main()
{
   typedef unsigned int UNIT;
   UNIT a,b;
   a=100;
   b=200;
   printf("Value of a is %d\n",a);
   printf("Value of b is %d \n",b);
   return 0;
}

In the above example, using typedef we renamed the datatype “unsigned int” to UNIT. Now UNIT can be used as a new type instead of unsigned int.

By convention, uppercase letters are used to remind the user that the type name is an abbreviation. But one can also use lowercase letters.

Output

Typedef with primitive datatypes

Typedef with user defined datatypes

typedef can also be used to give a name to user defined datatype too.

Example is shown below:

// C program to illustrate typedef
#include<stdio.h>
typedef struct students{
char name[50];
int roll_num;
}student1;
int main()
{
  student1 S1;
  printf("Enter the student details \n");
  printf("Enter the name of the student\n");
  scanf("%s",&S1.name);
  printf("Enter the roll_number of student\n");
  scanf("%d",&S1.roll_num);
  printf("Student name is %s \n",S1.name);
  printf("Student roll_number is %d \n",S1.roll_num);
  return 0;
} 

In the above code, student1 variable is used in a program to create the variable S1 of type struct students.

Output

Typedef with user defined datatypes

Typedef to rename pointer

typedef can also be used to rename pointer variables.

Example is shown below:

// C program to illustrate typedef with pointers
#include<stdio.h>
int main()
{
  typedef int * pointer;
  int var1=100;
  pointer p;
  p=&var1;
  printf("The value of variable var1 is %d \n",*p);
  return 0;
}

Output

Typedef with pointers

Difference between typedef and #define?

  • typedef is used to give symbolic names to types whereas #define can be used to define alias for values as well.
  • typedef interpretation is performed by the compiler whereas #define statements are processed by the preprocessor.
typedef#define
Used to give symbolic names to datatypes.Used to define alias for values.
Interpretation is performed by the compiler.Processed by preprocessor.

People also ask for

What is typedef in C?

typedef is a keyword that is used to rename the existing primitive and user-defined datatypes. Note that it doesn’t create a new type.


People also read