Typedef in C Language
In C language, typedef
is a keyword used to give a new name to an existing data type, allowing you to create an alias for that type. This can be useful for making code more readable and for abstracting away implementation details.
The syntax for a typedef
declaration is:
typedef <existing_data_type> <new_type_name>;
For example, you can create a new name for the int
data type like this:
typedef int my_int;
After this declaration, my_int
can be used as a new name for the int
data type. For example, you can declare a variable of type my_int
like this:
my_int x = 42;
This is equivalent to declaring a variable of type int
:
int x = 42;
You can also use typedef
to create new names for more complex data types, such as structures or pointers. For example, you can create a new name for a structure like this:
typedef struct {
int x;
int y;
} point;
After this declaration, point
can be used as a new name for the structure. For example, you can declare a variable of type point
like this:
point p = {1, 2};
This is equivalent to declaring a variable of the original structure type:
struct {
int x;
int y;
} p = {1, 2};
Using typedef
can make code more readable by creating more descriptive type names. For example, instead of declaring a variable of type int *
, you can create a new name for that type like this:
typedef int *int_ptr;
After this declaration, you can declare a variable of type int_ptr
like this:
int_ptr p = &x;
This is equivalent to declaring a variable of type int *
:
int *p = &x;