C Typedef
The typedef keyword lets you create an alias — a new name — for an existing type. This is often used to simplify complex type names, especially with structs, unions and pointers.
typedef doesn't create a genuinely new type; it just gives an existing type another name, which can make declarations shorter and more descriptive.
typedef existingType NewName;Simplifying struct names
Normally you must write `struct Point p;` to declare a variable. With `typedef struct { int x; int y; } Point;`, you can simply write `Point p;` instead.
Typedef with other types
typedef can alias any type, such as `typedef unsigned long ulong;`, making code shorter and sometimes clearer about intent.
#include <stdio.h>
typedef struct {
int x;
int y;
} Point;
int main() {
Point p = {1, 2};
printf("%d,%d\n", p.x, p.y);
return 0;
}1,2Point is now usable directly as a type name, without writing 'struct' each time.
#include <stdio.h>
typedef unsigned int uint;
int main() {
uint age = 25;
printf("%u\n", age);
return 0;
}25uint is now an alias for unsigned int, making declarations more concise.
Key points
- typedef creates an alias for an existing type.
- It doesn't create a genuinely new type, just a new name.
- It's commonly used to simplify struct and pointer type names.
- typedef names are conventionally written with a capital letter or _t suffix.
