Typedef Struct vs Struct Definitions in C

1. Overview

Structure (struct) is an important data type that helps to aggregate different data types into a single unit. However, the use typedef with struct can improve code usability and readability.

In this tutorial, we’ll delve into the differences between typedef struct and struct definitions in C with code examples.

2. struct in C

A struct is a user-defined data type that aggregates different data types into a single unit. It’s useful when we want to group related variables together.

Here’s a sample struct definition in C:

struct Book {
    char *name;
    int ISBN;
    float price;
};

In the code above, we define a struct called “Book“. It contains three variables of different data types.

Let’s declare a variable of this struct type:

struct Book book;
book.name = "Harry Potter";
book.ISBN = 12345;
book.price = 5000;

Here, we declare a variable of struct type Book and assign values to it.

Notably, we use the struct keyword to declare a new Book variable.

 3. typedef struct in C

While struct is incredible, it can become cumbersome to constantly write struct before every instance of our defined type, typedef solves this issue. typedef is a keyword in C that allows us to create an alias for existing data types. We can use it with struct to simplify the syntax for declaring struct variables.

Let’s redefine the Book struct with typedef:

typedef struct {
    char *name;
    int ISBN;
    float price;
} Book;

Therefore, we can declare a variable of this type without the struct keyword:

Book book;
book.name = "Harry Potter";
book.ISBN = 12345;
book.price = 5000;

Importantly, typedef doesn’t create a new data type, it only provides an alias for an existing one.

4. Conclusion

In this article, we learn how to use the struct and the typedef keywords in C. While struct allows us to aggregate different data types, typedef can simplify the syntax and improve code readability.

The complete source code for the examples is available on GitHub.