Table of Contents

C function pointers

C function pointers are pointers to functions, allowing callbacks, dispatch tables, and strategy patterns. Function pointers enable runtime dispatch without switch statements, making code extensible.

Use function pointers for callbacks, plugin systems, and decoupling behavior from callers.

Example

// compile: gcc -o func_ptr func_ptr.c
// run: ./func_ptr
// description: function pointers for dispatch
 
#include <stdio.h>
 
int add(int a, int b) { return a + b; }
int sub(int a, int b) { return a - b; }
int mul(int a, int b) { return a * b; }
 
typedef int (*Operation)(int, int);
 
int main() {
    Operation ops[] = {add, sub, mul};
    int x = 10, y = 3;
 
    printf("add: %d\n", ops[0](x, y));
    printf("sub: %d\n", ops[1](x, y));
    printf("mul: %d\n", ops[2](x, y));
 
    return 0;
}

Common patterns

Declaration syntax:

Callbacks:

Dispatch tables:

qsort and friends: