Site Tools


c-function-pointers

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:

  • int (*func_ptr)(int, int): pointer to function taking 2 ints, returning int
  • typedef int (*Operation)(int, int): clearer type alias

Callbacks:

  • Pass function pointer to register handler
  • Called later by library or event system

Dispatch tables:

  • Array of function pointers
  • Runtime selection without switch

qsort and friends:

  • Compare function passed as callback
  • Enables generic sorting
c-function-pointers.md · Last modified: by 127.0.0.1