C Typedef

Typdef is a C keyword which is used to define alternative names to existing datatypes. The general form of typedef statement is :
 typedef existing_datatype newname;
Example :
 typedef int num;
The above statement tells the compiler to recognize the word num as int data type. Now the term num can be used to int type variables, for example :
 num x,y,z;
The statement above is same as
 int x,y,z;
Now lets see a C example :
#include <stdio.h>

typedef int num;
typedef float frac; 

int main() {
  num a=15;
  frac x=12.87;

  printf("Integer : %d\n", a);
  printf("Float : %.2f\n", x);
  return 0;
}
Output :

Integer : 15
Float : 12.87

Applications of typedef in C :

The concept of typedef can be implemented for defining a user-defined data type with a specific name and type. Some of the application of typedef are :

1. With Structures :

The typdef can be used with structure in C. For example as we know that the structure definition is C will look like :
struct Book {
  char name[20];
  char author[20];
  int price;
};
Now we can create structure variable by below statement :
 struct Book b1, b1, b2;
Now at here by using typedef keyword with the structure definition we can directly create the structure variable without using the struct keyword. For Example :
typedef struct {
  char name[20];
  char author[20];
  int price;
} book;
At above statement in the last line book represents the structure definition associated with it. Now by using the struct alias book we can create structure variables. For example :
 book b1, b2;
C Example Code :
#include <stdio.h>
#include <string.h>

typedef struct {
  char name[20];
  char author[20];
  int price;
} book;

int main() {
  book b1, b2;

  strncpy(b1.name, "C Programming", 20);
  strncpy(b1.author, "Dennis Ritchie", 20);
  b1.price = 250;


  strncpy(b2.name, "C Sockets", 20);
  strncpy(b2.author, "John Forgers", 20);
  b2.price = 230;


  printf("Book Details :\n\n");
  printf("Name : %s\n", b1.name);
  printf("Author : %s\n", b1.author);
  printf("Price : %d\n\n", b1.price);

  printf("Name : %s\n", b2.name);
  printf("Author : %s\n", b2.author);
  printf("Price : %d\n", b2.price);

  return 0;
}
Output :

Book Details :

Name : C Programming
Author : Dennis Ritchie
Price : 250

Name : C Sockets
Author : John Forgers
Price : 230

2. With Pointers :

The typedef keyword can also be used with in the pointers. In C language the pointers are declared using datatype followed by asterisk ( * ) sign :
 datatype* pointer_name;
Example :
 int* ptr;
At this place we can create an alias for int* to create pointer variables :
 typedef int* iptr;
Now by using iptr we can create integer pointers.
 iptr x,y;
C example Code :
#include <stdio.h>

typedef int* iptr;

int main() {
  int a = 20;
  int b = 30;

  iptr x,y;

  x = &a;
  y = &b;

  printf("Numbers : %d, %d\n", *x, *y);
  return 0;
}
Output :

Numbers : 20, 30

Next Topic :