Skip to content
FollowtheDamnCode

typedef

Giving a type a shorter name.

3 minute read

Big idea

typedef gives an existing type a new, shorter name. It's most useful for structs, so you can write Point instead of struct Point.

The idea

typedef existing_type new_name;
typedef unsigned long long u64;   // now u64 means unsigned long long
u64 big = 18000000000ULL;

With structs, you can name the type as you define it:

typedef struct {
    int x;
    int y;
} Point;

Point p = {3, 4};    // no "struct" needed
A tiny geometry library with typedef
#include <stdio.h>

typedef struct {
    int x;
    int y;
} Point;

typedef struct {
    Point top_left;
    Point bottom_right;
} Rect;

int area(Rect r) {
    int w = r.bottom_right.x - r.top_left.x;
    int h = r.bottom_right.y - r.top_left.y;
    return w * h;
}

int main(void) {
    Rect r = {{1, 2}, {6, 5}};
    printf("%d\n", area(r));
    return 0;
}
output
15

Run and edit it in the app.

Rect holds two Points, so r.bottom_right.x reads "the rectangle's bottom-right point's x" — structs can nest.

Watch it

It doesn't create a new type

typedef only adds a nickname. u64 and unsigned long long are the same type; the compiler treats them identically. It's there for readability: Celsius temp; says more than double temp;.

Predict: typedef names are just nicknames
#include <stdio.h>

typedef int Score;

int main(void) {
    Score a = 7;
    int b = a * 2;
    Score c = b + 1;
    printf("%d %d %d %d\n", a, b, c, sizeof(Score) == sizeof(int));
    return 0;
}
What does it print? Show the answer
7 14 15 1

Run and edit it in the app.

Naming habits

  • Many codebases use CapitalCase for typedef'd structs (Point, Student) so they stand out from variables.
  • Avoid names ending in _t for your own types — the C standard library reserves them (size_t, int64_t).

Think of it like

Saving a contact as "Mum" instead of her full name and number. It's the same person — just quicker to find.

🕷️ Spidey-sense: Everyone else says "the Amazing Spider-Man", I say typedef and go with Spidey. Same hero, fewer syllables.

Key terms

  • typedef — Creates an alias (a new name) for an existing type.
  • Alias — Another name for the same thing.
  • Nested struct — A struct that has another struct as a member.

Check yourself

What does typedef do?

After typedef struct { int x, y; } Point; how do you declare one?

Which names should you avoid for your own types?