How to use the typedef struct in C

Key takeaways

  • typedef allows us to create simpler names for complex data types such as struct, improving code readability.

  • Use typedef to avoid repeating the struct keyword in variable declarations.

  • typedef struct helps us to maintain consistent type names across the codebase.

  • typedef structures can be passed to functions either by value or by reference.

Calling elements by their full paths or full names can be cumbersome when writing the code. Imagine you are developing a social media app and need to manage user profile details. To do this, you can define a struct UserProfile data type to encapsulate all attributes of the user profile (e.g. name, age, gender, ID, etc.). Now, you have to write out the full type name like struct UserProfile every time you use it. Instead of repeatedly writing out the full type name like struct UserProfile, C programming language allows us to use a simpler alias like UserProfile or Profile.

What is the typedef keyword?

C offers the typedef keyword to allow users to specify alternative simple and desired names for the primitive (e.g. int) and user-defined data types (e.g. struct). The typedef simplifies the use of complex data structures by allowing us to define a shorter, more convenient name for them. typedef can be a form of documentation by providing meaningful names for complex types.

“Good code is its own best documentation”—Steve McConnell

Where to put typedef struct in C?

For structures, the C typedef keyword offers us to define a new type name for a structure, making the code more readable and maintainable. Here is the syntax to use typedef for structure data type:

struct structName {
type member1;
type member2;
// ...
};
typedef struct structName typedefName;
//Second way to define typedef keyword
typedef struct structName {
type member1;
type member2;
// ...
} typedefName;
Syntax for typedef in C

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.

Remember, typedef keyword adds a new name for some existing data type but does not create a new type.

How to use typedef struct in C code

The following code snippets first demonstrate the code without defining a struct using typedef, and then explain how to use a C keyword typedef for structures.

1. Structure declaration without using typedef

The following code example demonstrates the struct 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 if we use the typedef keyword with a struct, there is no longer a need to type struct again and again with every declaration of the variable of this type.

Method 1: Using typedef separately from the structure definition

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 2: Using typedef with the structure definition

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

How to pass a typedef structure to a function in C

We can pass typedef structure to a function in C in the following way:

  • Define struct using typedef keyword.

  • Declare and define a function that will accept the structure.

  • Decide which method to use to pass the structure—pass by value or pass by reference.

  • Call the function.

Here is the code example of passing a typedef struct to a function in C in both ways: passing by value and by reference.

#include <stdio.h>
// Define a structure named Point with two integer members: x and y
typedef struct Point {
int x;
int y;
} Point;
// Function to print a Point structure by value
void printPointByValue(Point p) {
printf("x: %d, y: %d\n", p.x, p.y);
}
// Function to print a Point structure by reference
void printPointByReference(Point *p) {
printf("x: %d, y: %d\n", p->x, p->y);
}
int main() {
// Declare a variable named p1 of type Point
Point p1;
// Initialize p1's members directly
p1.x = 1;
p1.y = 3;
// Pass by value
printPointByValue(p1);
// Pass by reference
printPointByReference(&p1);
return 0;
}

Advantages of typedef struct in C

Let’s discuss some of the typedef advantages for structures:

  • It simplifies type declarations.

  • It ensures consistency across the codebase.

    • If we need to change the structure or type, we only need to update the typedef definition in one place, rather than updating every instance where the type is used.

  • It improves code readability.

Quiz

Evaluate your understanding by solving the quiz below.

1

What is the syntax for typedef in C?

A)
struct structName {
    type member1;
    type member2;
    // ...
};
typedef typedefName;
B)
typedef struct structName {
    type member1;
    type member2;
    // ...
};
C)
typedef struct structName {
    type member1;
    type member2;
    // ...
} typedefName;
D)

None of them

Question 1 of 50 attempted

Frequently asked questions

Haven’t found what you were looking for? Contact Us


What is the difference between struct and typedef struct?

struct and typedef struct are two C keywords. struct is used to define a structure that groups multiple data items of possibly different data types into a single collection. On the other hand, typedef struct is used to create an alias for an existing structure.


What is the difference between typedef and #define?

typedef creates aliases for data types, provides names to type like defining float as Temperature to represent temperature values. On the other hand, #define establishes symbolic constants or macros, such as using #define MAX_STUDENTS 100 to represent the maximum number of students.


Why #define is used?

#define is a preprocessor directive that has the following structure:

#define identifier replacement-text

Before compilation, the compiler replaces any occurrences of identifier that don’t occur as part of a string literal or a comment with the replacement-text. This allows #define to create Symbolic Constants and Macros.


How can we use struct in C?

We can use struct in C by defining, initializing, and accessing a structure. Here is the basic syntax to define struct in C:

struct structure_name
{
    //data_type variable 1
    //data_type variable 2
    ...
};

For more details on C struct, check out our detailed Answer on What is a C struct?.


Is typedef struct needed in C?

typedef is optional in C. We can use it to make the code cleaner and easier to manage.


How can typedef be used with arrays?

typedef is used with arrays by creating an alias for array types. For example, typedef int student_array[10]; allows us to use student_array as a shorthand for an array of 10 integers.


Does typedef create a new type?

typedef does not create a new type. It is used to create an alias for an existing type.


Is there any equivalent to typedef of C/C++ in Java?

No, Java doesn’t provide any equivalent to typedef. Usually, Java manages types through classes and interfaces rather than type aliases.


How do we define a typedef for a function pointer in C?

We can create a typedef for function pointer in the following way:

typedef return_type (*alias_name)(parameter_types);

Here, typedef is the keyword used to create an alias for an existing type, return_type indicates the return type of the function that the pointer will point to, (*alias_name) for the function pointer, the * indicates that this is a pointer to a function, and the (parameter_types) represents the types of parameters that the function takes.


How do we use typedef for a union in C?

We can use typedef for a union in C using the following syntax:

typedef union unionName {
    //data_type variable 1
    //data_type variable 2
    ...
} typedefName;

Copyright ©2024 Educative, Inc. All rights reserved