Labs ICT
โญ Pro Login

Typedef

2 min read | C Tutorial
โญ

Want the full learning experience?

Get structured courses, certificates, projects, and instructor support with LabsICT Pro.

Explore Pro Courses

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 <stdio.h>
typedef int Age;
int main() {
  Age myAge = 25;
  printf("I am %d years old\n", myAge);
  return 0;
}
    

typedef with Structs

This is where typedef really shines. Instead of struct Point p, you can just write Point p.


#include <stdio.h>
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;
}
    

typedef for Function Pointers

Function pointer syntax is ugly. typedef makes it readable by hiding the pointer mechanics behind a clean alias.


#include <stdio.h>
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;
}
    

๐Ÿงช Quick Quiz

What does typedef do?