typedef
typedef creates a new name — an alias — for an existing type. It does not create a new type in any deep sense; it simply gives you another, often shorter or clearer, way to write a type that already exists. Its most valuable use is taming complicated declarations that would otherwise be hard to read.
Basic syntax
#include <stdio.h>
typedef unsigned long ulong_t;
int main(void) {
ulong_t big_number = 4000000000UL;
printf("%lu\n", big_number);
return 0;
}4000000000
Simplifying struct declarations
Without typedef, referring to a struct type requires writing struct every time: struct Point p;. A very common C idiom pairs an anonymous struct definition with a typedef so you can drop the struct keyword afterward:
#include <stdio.h>
typedef struct {
int x;
int y;
} Point;
// Without the typedef, this parameter would have to be "struct Point *p"
void print_point(Point *p) {
printf("(%d, %d)\n", p->x, p->y);
}
int main(void) {
Point origin = {0, 0};
print_point(&origin);
return 0;
}(0, 0)
Simplifying pointer and function pointer types
typedef is especially valuable for function pointer types, whose raw syntax is notoriously hard to read. Compare declaring several variables of a function pointer type directly versus through a typedef:
// Without typedef: every variable repeats the full, awkward syntax.
int (*op1)(int, int);
int (*op2)(int, int);
// With typedef: define the type once, then use it like any other type.
typedef int (*BinaryOp)(int, int);
BinaryOp op3;
BinaryOp op4;
int add(int a, int b) { return a + b; }
int main(void) {
BinaryOp op = add;
return op(2, 3) == 5 ? 0 : 1;
}typedef existing_type new_name;creates an alias, not a new type.The
typedef struct {...} Name;pattern lets you writeNameinstead ofstruct Nameeverywhere.Function pointer types benefit the most — a typedef turns an unreadable declaration into a reusable, readable name.
Two typedefs of the same underlying type are fully interchangeable; typedef adds no type safety of its own.