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

Forward declarations of structs

Forward declarations of structs

What you'll learn: How to define structures that refer to each other by telling the C compiler a specific name exists before you fully define it.

The Chicken and the Egg Problem

In C, the compiler reads your code from top to bottom. This creates a logical puzzle when two structures need to know about each other. Imagine a simple game involving a Pilot and a Starship. The Pilot needs to know which Ship they are flying, and the Ship needs to know who its Pilot is.

If you define the Pilot struct first, the compiler will complain because it hasn't seen the Starship struct yet. If you swap them, you have the same problem in reverse. They are "mutually dependent."

The "Save the Date" of Programming

A forward declaration solves this by giving the compiler a heads-up. It’s like sending a "Save the Date" card before the formal wedding invitation. You are telling C, "Hey, there is a structure named Starship coming later. Just trust me for now."

Because a pointer (like struct Starship *ship) is always the same size in memory regardless of what it points to, the compiler doesn't need the full details of the struct to proceed—it just needs to know that the name represents a structure.

How to implement it

To create a forward declaration, you simply write struct Name; on its own line before your actual definitions.

#include <stdio.h>

// 1. Forward Declaration: "Trust me, this exists."
struct Starship;

// 2. Define the first struct using a pointer to the second
struct Pilot {
    char name[50];
    struct Starship *current_craft; 
};

// 3. Define the second struct
struct Starship {
    char model[50];
    struct Pilot *captain;
};

int main() {
    struct Pilot p1 = {"Han Solo", NULL};
    struct Starship s1 = {"Millennium Falcon", &p1};
    
    // Connect them
    p1.current_craft = &s1;

    printf("%s is flying the %s.\n", p1.name, p1.current_craft->model);
    return 0;
}

When to use this

You will use forward declarations most often in complex data structures, such as linked lists or graphs, where nodes might point back and forth to each other. By declaring the struct name early, you break the circular dependency and allow the compiler to build the relationships without getting confused.

Key takeaway

Forward declarations let you use a struct name before it is fully defined, which is essential for structures that refer to one another.