Typing struct Student over and over gets old fast. typedef lets you create a nickname for a type โ shorter, cleaner, and easier to read.
Basic typedef
With typedef, you define an alias. After that, you can use the alias just like any other type name.
#include
typedef int Age;
int main() {
Age myAge = 25;
printf("I am %d years old\n", myAge);
return 0;
}
Try it Yourself โ
typedef with Structs
This is where typedef really shines. Instead of struct Point p, you can just write Point p.
#include
typedef struct {
double real;
double imag;
} Complex;
int main() {
Complex c1 = {3.5, 2.1};
Complex c2 = {1.0, 4.3};
Complex sum;
sum.real = c1.real + c2.real;
sum.imag = c1.imag + c2.imag;
printf("Sum: %.1f + %.1fi\n", sum.real, sum.imag);
return 0;
}
Try it Yourself โ
typedef for Function Pointers
Function pointer syntax is ugly. typedef makes it readable by hiding the pointer mechanics behind a clean alias.
#include
typedef int (*Operation)(int, int);
int add(int a, int b) { return a + b; }
int multiply(int a, int b) { return a * b; }
int main() {
Operation op = add;
printf("Result: %d\n", op(3, 4));
op = multiply;
printf("Result: %d\n", op(3, 4));
return 0;
}
Try it Yourself โ