C typedef

The typedef keyword lets you create a new, friendlier name for an existing type. It does not create a new type; it just gives an alias. This is especially useful with structures, where it lets you drop the repetitive struct keyword every time you declare a variable.

Aliasing basic types

In its simplest form, typedef takes an existing type and an alias name. After that, the alias can be used anywhere the original type could be used, which can make code easier to read and adjust later.

A simple typedef

#include <stdio.h>

typedef unsigned int uint;

int main() {
    uint count = 5;
    printf("Count is %u\n", count);
    return 0;
}

typedef with structures

The most common use of typedef is with structs. Normally you must write struct Book every time you declare one. By adding a typedef, you can refer to it with a single word.

Cleaner structs with typedef

#include <stdio.h>

typedef struct {
    char title[30];
    int pages;
} Book;

int main() {
    Book b = {"C Basics", 240};   // no 'struct' keyword needed

    printf("%s has %d pages\n", b.title, b.pages);
    return 0;
}

Here Book becomes the name of the type. You declare variables as Book b instead of struct Book b, which reads more naturally and saves typing across a large program.

  • typedef creates an alias, not a brand new type.
  • It is very common to typedef structs so you can omit the struct keyword.
  • Aliases make it easy to swap the underlying type in one place later.
  • The alias name conventionally starts with a capital letter for structs.
Without typedefWith typedef
struct Book b;Book b;
struct Point p1, p2;Point p1, p2;
unsigned int x;uint x;
Note: You can combine the struct definition and the typedef in one statement, as shown above, or write them separately. Both approaches produce the same usable alias.