Why typedef keyword is used for?

Typedef keyword is mostly used with structure to provide variable name that have already existed. It works like as defining alias name for data type.

In this article we will know details about typedef keyword. Here is the syntax of typedef in C.

// syntax of typedef keyword in C

typedef <existing_name> <alias_name>

Here in this example existing_name is an already existing name of a variable where alias_name is the given name of the variable.

The example bellow will clear your idea about typedef keyword in C. Here we have declared an int variable and then declare multiple variables of same type using typedef keyword.

// declaring variables with typedef

typedef int num;

num a, b, c, d;

Here in the example we have declared an int variable using typedef. Now, we can declare the int type variable by just write num followed by the name of variable like a, b, c, d etc.

typedef is used where we need a long data type as like structure because it provides a very effective shortcut to declare the same variable.

Now, we will see an example program using typedef keyword in C.

Example C program using typedef keyword

In this program we will find the sum of two integers using typedef keyword to declare variable.

// C program with typedef keyword
#include <stdio.h>
int main(){
  typedef int num;
  num a, b, c;

  a = 10;
  b = 20;
  c = a + b;

  printf("Sum of a and b is = %d\n", c);

  return 0;
}

Program output

typedef in c, typedef keyword in c

typedef with structure in C

We can use typedef with C structure by the any of the following way.

First way :

// first way of using typedef with structure in C

struct employee{
  int id;
  char name[30];
  int age;
  float salary;
};

typedef struct employee emp;

emp e1, e2, e3, e4;

Second way :

// second way of using typedef with structure in C

typedef struct employee{
  int id;
  char name[30];
  int age;
  float salary;
} emp;

emp e1, e2, e3, e4;

Example program using typedef with structure

In this program we will store students information in a structure and then print these information. All this things we will do here using typedef keyword with structure in C.

// use of typedef with structure in a C program

#include <stdio.h>
typedef struct student_info{
  char name[30];
  int roll;
  int age;
  float cgpa;
}student;

int main(){
  student s1;
  printf("Enter details of student 1 here : \n");

  printf("\nName : ");
  scanf("%s",&s1.name);

  printf("Roll no : ");
  scanf("%d",&s1.roll);

  printf("Age : ");
  scanf("%d",&s1.age);

  printf("CGPA : ");
  scanf("%f",&s1.cgpa);

  printf("\nName of the student 1 is : %s\n", s1.name);
  printf("His roll no is : %d\n", s1.roll);
  printf("He is %d years old.\n", s1.age);
  printf("And his CGPA is %.2f\n", s1.cgpa);

  return 0;
}

You will see the following output after you have compiled and run this program.

Previous pageStructure in C language

Next pageArray of structure