Course contentsShow
← C
Lesson 520 of 1,2197. PointersFree lesson

Defining `typedef` for function pointers

Defining typedef for function pointers

What you'll learn: How to use the typedef keyword to simplify the complex syntax of function pointers and make your code more readable.

The problem with raw syntax

Function pointers are incredibly powerful, but their syntax is notoriously messy. If you want to declare a pointer to a function that takes two integers and returns an integer, it looks like this: int (*operation)(int, int);.

Every time you want to pass this pointer into another function or create an array of these pointers, you have to type that entire "sandwich" of parentheses and asterisks. It’s like having to write out a full legal name and home address every time you refer to a friend in conversation. It works, but it’s exhausting and prone to typos.

Using typedef as a nickname

In C, the typedef keyword allows you to create an alias for a data type. When applied to function pointers, it acts like a "blueprint." Instead of writing the full signature every time, you define the signature once and give it a simple, catchy name.

Think of it like a job title. Instead of saying "the person who handles the cash register and bags the groceries," you just say "Cashier."

How it looks in code

By using typedef, you can treat your function pointer signature like a custom type, similar to int or float.

#include <stdio.h>

// 1. Define the blueprint: A 'MathFunc' is any function 
// that takes two ints and returns one int.
typedef int (*MathFunc)(int, int);

int add(int a, int b) { return a + b; }
int multiply(int a, int b) { return a * b; }

int main() {
    // 2. Use the nickname instead of the messy syntax
    MathFunc op; 

    op = add;
    printf("Sum: %d\n", op(10, 5));

    op = multiply;
    printf("Product: %d\n", op(10, 5));

    return 0;
}

Why this matters

Without typedef, a function accepting a function pointer as a parameter looks like a bowl of alphabet soup: void compute(int a, int b, int (*op)(int, int)).

With the typedef defined above, it becomes clean and intuitive: void compute(int a, int b, MathFunc op). This makes your code self-documenting. Anyone reading your code immediately understands that op belongs to the MathFunc family, making your programs much easier to maintain.

Key takeaway

Use typedef to turn complex function pointer signatures into simple, reusable type names that act as blueprints for your functions.