The C language contains the typedef
keyword to allow users to provide alternative names for the primitive (e.g., int) and user-defined (e.g struct) data types.
Remember, this keyword adds a new name for some existing data type but does not create a new type.
Here is the syntax to use typdef
for primitive and user-defined data types.
typedef <existing_type> <alias>
Using typedef struct
results in a cleaner, more readable code, and saves the programmer keystrokes. However, it also leads to a more cluttered global namespace which can be problematic for large programs.
The following code snippets illustrate how to use the typedef struct
.
typedef
:#include<stdio.h>struct Point{int x;int y;};int main() {struct Point p1;p1.x = 1;p1.y = 3;printf("%d \n", p1.x);printf("%d \n", p1.y);return 0;}
typedef
keyword:Note that there is no longer a need to type struct
again and again with every declaration of the variable of this type.
In the code below,
the structure Point
is defined separately using struct Point
, and then a typedef
is applied to create an alias Point
for this structure. This allows us to declare variables of this structure type using just Point
.
#include<stdio.h>struct Point{int x;int y;};typedef struct Point Point;int main() {Point p1;p1.x = 1;p1.y = 3;printf("%d \n", p1.x);printf("%d \n", p1.y);return 0;}
The typedef
is applied directly to the structure definition itself. This combines the definition of the structure and the creation of the alias Point
in a single statement.
#include<stdio.h>// Define a structure named Point with two integer members: x and ytypedef struct Point{int x;int y;} Point;int main() {// Declare a variable named p1 of type PointPoint p1;p1.x = 1;p1.y = 3;printf("%d \n", p1.x);printf("%d \n", p1.y);return 0;}
RELATED TAGS