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

Typedef vs. #define macros

Typedef vs. #define macros

What you'll learn: Why you should use typedef to create type aliases instead of relying on the preprocessor's text-replacement tool.

In earlier lessons, you likely used #define to create constants. While it is tempting to use #define to create shortcuts for complex structure names, it can lead to frustrating bugs. In C, typedef is the proper tool for creating type aliases because it understands the language's grammar, whereas #define is just a blind "search and replace" tool.

The Blind Search-and-Replace

Think of #define as a clumsy intern who literally swaps words in your document before the compiler even looks at it. If you write #define STRING char*, and then try to declare two strings on one line like this:

STRING a, b;

The preprocessor replaces the word STRING, and the compiler sees:

char* a, b;

In C, this results in a being a pointer to a character, but b being a plain character. This is almost never what you intended!

The Intelligent Alias

A typedef, on the other hand, is handled by the compiler itself. It doesn't just swap text; it creates a genuine alias for the type. It’s like giving a person a nickname—whether you call them "Robert" or "Bob," they are still the same human being with the same properties.

When you use typedef for a pointer or a structure, the compiler ensures that every variable declared with that alias behaves exactly like the original type, even in lists.

#include <stdio.h>

// Using typedef to make a struct easier to use
typedef struct {
    int x;
    int y;
} Point;

// Defining a pointer alias correctly
typedef int* IntPtr;

int main() {
    // Both p1 and p2 are full Point structures
    Point p1, p2;
    
    // Both ptr1 and ptr2 are actual integer pointers
    IntPtr ptr1, ptr2;
    
    int val = 42;
    ptr1 = &val;
    ptr2 = &val;

    printf("Pointer 2 value: %d\n", *ptr2);
    return 0;
}

Why it matters

Using typedef provides type safety. The compiler can provide better error messages because it knows the alias refers to a specific type. If you use #define, the compiler only sees the raw code after the replacement, making debugging much harder. When working with structures or pointers, always choose typedef to ensure your code behaves predictably.

Key takeaway

Use typedef for type aliases because it obeys C’s scoping and declaration rules, unlike #define which performs simple, literal text substitution.