Typedef for Portability

Typedef is used to change the name of any standard library data type.

We are using int data type. If we want to change the name of int to any other name then we use typedef. In this, wherever we want to write keyword “int” data type then instead of keyword “int” we use the user-defined name of data type int.

In short, the keyword int is replaced by a user-defined name. Same for other data types. The syntax for the same is written below.

typedef   <name of data type>   <userdefined name>;

Here the 1st program is showing a simple program using int. We have one int variable i and we are printing its value.

#include <stdio.h>
#include <conio.h>
void main()
{
    int i=2;
  clrscr();
    printf("%d",i);
    getch();
}

Output:

The 2nd program works the same as the 1st program. Just the “int” keyword is replaced by a user-defined name “coding”. So “coding” is an alternative name of int in this program.

Wherever we are supposed to write the keyword “int” instead of that we can write “coding”. Same as “coding” we can give any user-defined name instead of the keyword of any data type. 

#include <stdio.h>
#include <conio.h>
void main()
{	
  //here we are replacing int keyword to coding
  typedef int coding;	
  //Below, i is of type coding, as coding is int so i is int
  coding i=2;
  clrscr();
  printf("%d",i);
  getch();
}

Output:

Need of typedef

The size of any data type may change from processor to processor.

Some have size of int data type 2 bytes(16-bit microprocessor) and some have the size of int data type 4 bytes(32-bit microprocessor). If we run the code of a processor whose int size is 2 bytes to other processors it may create some problem for those systems whose int size is 4 bytes because of different sizes in memory.

So this creates a problem because for the 16-bit microprocessor, the size of int data type is 2 bytes and for the 32-bit microprocessor, the size of int data type is 4 bytes. So when we write a code then we make a user-defined name of the data type in that way which shows the size of that data type.

 typedef int int_2bytes

This shows that this code is made according to int having 2 bytes size. Let us take an example of a 32-bit processor.

typedef int int_4bytes 

This shows that this code is made according to int size 4 bytes. So this shows good portability.

Learning from this blog:

  1. Meaning of typedef.
  2. Need of typedef.
  3. Difference between simple int and int with typedef.
  4. Syntax of using typedef.
  5. How the use of typedef is related to portability.
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments