Trusted answers to developer questions

How to use the typedef struct in C

Get Started With Data Science

Learn the fundamentals of Data Science with this free course. Future-proof your career by adding Data Science skills to your toolkit — or prepare to land a job in AI, Machine Learning, or Data Analysis.

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.


Syntax

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.

Examples

The following code snippets illustrate how to use the typedef struct.

1. Variable declaration without using 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;
}

2. Using the 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.

Method one:

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;
}

Method two:

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 y
typedef struct Point{
int x;
int y;
} Point;
int main() {
// Declare a variable named p1 of type Point
Point p1;
p1.x = 1;
p1.y = 3;
printf("%d \n", p1.x);
printf("%d \n", p1.y);
return 0;
}

RELATED TAGS

c
struct
keyword
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?