In the C programming language, typedef helps in creating an alias or giving a new name for the existing data type. Using typedef keyword we can create a temporary name for the existing data type be it system-defined data type or user-defined data type.
Syntax:
typedef <existing_data_type> <alias-name>
Example:
typedef with int
#include <stdio.h>
typedef int Number;
int main ()
{
Number x = 10;
Number y =20;
Number sum = x + y;
printf("\n Sum is: %d\n", sum);
return 0;
}
In the above example, Number is a new name to type “int”. Hence the data type “Number” can be used in place of int.’
typedef with Arrays:
#include <stdio.h>
int main ()
{
typedef array[5];
array list = {1, 2, 3, 4, 5};
int i = 0;
for (i = 0; i < 5; i++)
printf("\n %d ", list[i]);
return 0;
}
typedef with structure:
#include <stdio.h>
struct College_student
{
char name[10];
int roll;
};
int main()
{
typedef struct College_student STUD; /* Alias name STUD */
STUD stud;
stud.roll =5;
printf ("\n Roll number is %d\n", stud.roll);
return 0;
}
typedef with Pointers:
#include <stdio.h>
int main ()
{
typedef int* intPointer;
intPointer ptr;
int a = 10;
ptr = &a;
printf("\n The value is %d\n", *ptr);
return 0;
}
Importance of typedef:
- It helps to organize the code better by giving more appropriate name for the user defined data type.
- It makes the program loose coupling with machine that is better portability.
- It helps in better documentation and also make the program more readable.
How it helps in portability:
i) int x
ii) typedef int new_name
The second is best suited because in the future if any of the machines do not support type ‘int’ and support ‘float’ we can just change the typedef statement rather than changing it at multiple places in the code.
Relevant Posts:
- Structure in C
- Union in C
- Function in C
- Difference between structure and union
- Structure padding
- Array of structure
- Pointer to structure
Categories: C Language
Leave a Reply