Course contentsShow
← C
Lesson 611 of 1,2199. Structures and UnionsFree lesson

Anonymous structs with typedef

Anonymous structs with typedef

What you'll learn: How to simplify your code by combining structure definitions with type aliases to skip redundant naming.

In the previous lesson, you learned that every time you want to use a struct, you have to lug around the struct keyword, like writing struct Point p1;. This can feel repetitive. While typedef allows us to create a nickname for an existing struct, we can actually go one step further: creating a "nameless" or anonymous struct that exists only through its alias.

The "Nickname Only" Approach

Think of a standard struct definition like a formal legal name (e.g., "The Residential Building at 123 Maple St") and a typedef as a short nickname ("The Cabin"). Usually, you define the formal name first, then assign the nickname.

With an anonymous struct, you tell C: "I don't care about a formal name. Just call this shape 'The Cabin' from now on."

In code, this means we omit the tag (the name that usually follows the word struct) and provide the alias at the very end.

#include <stdio.h>

// We skip the name after 'struct' and go straight to the alias 'Monster'
typedef struct {
    int health;
    int level;
} Monster;

int main() {
    // Now we don't need the 'struct' keyword anymore!
    Monster goblin;
    
    goblin.health = 100;
    goblin.level = 5;

    printf("Goblin Level: %d", goblin.level);
    
    return 0;
}

Why use this?

The main benefit is cleaner code. By using an anonymous struct with typedef, you treat your custom data type exactly like a built-in type (such as int or float).

When you use a standard struct name (like struct Player), you are telling the compiler about a "tag." When you use typedef, you are creating a new name in the global type list. By leaving the struct anonymous, you prevent "namespace clutter"—you don't have to think of two different names for the same thing (one for the struct tag and one for the typedef). It is the most common way to define data structures in modern C development.

Key takeaway

Anonymous structs combined with typedef allow you to define a data structure and its nickname in one step, letting you declare variables without using the struct keyword.