Skip to content
C

Function Pointers

Store function addresses for callbacks and dispatch tables.

By EZ4Code Team
function-pointercallback

Code

#include <stdio.h>

// A function pointer type
typedef int (*BinOp)(int, int);

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

int apply(BinOp op, int a, int b) {
    return op(a, b);
}

int main(void) {
    BinOp op = add;
    printf("add(2,3) = %d\n", op(2, 3));

    op = mul;
    printf("mul(2,3) = %d\n", op(2, 3));

    // Dispatch table
    BinOp table[] = {add, mul};
    for (int i = 0; i < 2; i++) {
        printf("table[%d](4,5) = %d\n", i, table[i](4, 5));
    }
    return 0;
}

Explanation

A function pointer stores the address of a function so it can be called indirectly, enabling callbacks and dispatch tables. The typedef BinOp makes the pointer-to-function syntax readable. Functions like qsort use this mechanism to let callers supply their own comparison logic.

More C Snippets