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.
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.
#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; }
#include<stdio.h> typedef struct Point{ int x; int y; } Point; int main() { Point p1; p1.x = 1; p1.y = 3; printf("%d \n", p1.x); printf("%d \n", p1.y); return 0; }
RELATED TAGS
View all Courses