Creating a shorthand for struct names
What you'll learn: How to use typedef to simplify your code by turning long structure declarations into short, easy-to-use custom types.
The problem: Repetitive typing
In C, when you define a structure, the compiler treats the two-word phrase struct Name as the full type. Imagine you have a structure for a 2D coordinate called Point. Every time you want to create a new variable, you have to type the word struct:
struct Point {
int x;
int y;
};
struct Point p1; // A bit wordy!
If you are writing a graphics program with hundreds of points, writing struct over and over feels like a chore. It clutters your code and makes it harder to read.
The solution: typedef
Think of typedef (short for "type definition") as a way to create a nickname or an alias for an existing type. It’s like how you might call a "North American Trash Panda" a "Raccoon." The animal hasn't changed, but the name is much easier to use in conversation.
When we combine typedef with a struct, we tell C: "From now on, whenever I say Point, I mean struct Point."
How to use it
You can apply typedef directly to the structure definition. The most common pattern looks like this:
#include <stdio.h>
// We define the struct and give it an alias all at once
typedef struct {
int x;
int y;
} Point;
int main() {
// No 'struct' keyword needed here!
Point p1;
p1.x = 10;
p1.y = 20;
printf("Point is at %d, %d\n", p1.x, p1.y);
return 0;
}
In the example above, Point (at the very end of the definition) becomes the new name for the entire structure block. We no longer need to type struct when declaring p1.
Why bother?
Using typedef makes your custom structures feel like built-in types, just like int or char. It makes your code cleaner, reduces the chance of typos, and follows the standard practice used in professional C libraries. It transforms a complex data structure into a simple, recognizable "object" name.
Key takeaway
Use typedef with structures to create a one-word alias, allowing you to declare variables without repeatedly typing the struct keyword.