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.
// 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; }
Declaration syntax:
int (*func_ptr)(int, int): pointer to function taking 2 ints, returning inttypedef int (*Operation)(int, int): clearer type aliasCallbacks:
Dispatch tables:
qsort and friends: