C programming - typedef

www.igi‮‬ftidea.com

In C programming, the typedef keyword is used to create an alias for an existing data type. It allows you to define a new name for an existing data type that can be used interchangeably with the original data type.

The syntax for using the typedef keyword is as follows:

typedef <existing_data_type> <new_data_type>;

Here, <existing_data_type> is the name of the existing data type for which you want to create an alias, and <new_data_type> is the name of the new data type.

For example, consider the following code:

#include <stdio.h>

typedef unsigned char byte;

int main() {
   byte a = 'A';
   printf("Value of a: %c\n", a);
   return 0;
}

Here, we have defined a new data type byte that is an alias for the unsigned char data type. We then use the byte data type to declare a variable a and assign it the value 'A'. Finally, we print the value of a.

The typedef keyword is often used to make code more readable and to simplify the declaration of complex data types such as structures and pointers. For example:

typedef struct {
   int x;
   int y;
} point;

typedef int (*func_ptr)(int);

In the above code, we define two new data types point and func_ptr. The point data type is an alias for a structure that contains two integer fields x and y. The func_ptr data type is an alias for a pointer to a function that takes an integer argument and returns an integer.