AdvancedLesson 14 of 18
Function Pointers & Callbacks – C
Functions as values: callbacks, qsort and dispatch tables.
Functions have an address too. A function pointer stores it, so you can pass functions as arguments or put them in tables. You read the declaration from the inside: int (*op)(int, int) – "op is a pointer to a function (int, int) that returns int". The parentheses around *op are crucial.
#include <stdio.h>
int add(int a, int b) { return a + b; }
int sub(int a, int b) { return a - b; }
void fuer_jedes(const int *a, size_t n, void (*f)(int)) {
for (size_t i = 0; i < n; i++) f(a[i]);
}
void zeige(int x) { printf("<%d>", x); }
int main(void) {
int (*op)(int, int) = add;
printf("%d\n", op(2, 3)); // 5
op = sub;
printf("%d\n", op(2, 3)); // -1
int z[] = {1, 2, 3};
fuer_jedes(z, 3, zeige); // callback
printf("\n");
return 0;
}The standard library uses this principle in qsort and bsearch: you only supply the comparison function (returning negative, 0 or positive), while the sorting logic lives in the library.
#include <stdio.h>
#include <stdlib.h>
int aufsteigend(const void *a, const void *b) {
int x = *(const int *)a;
int y = *(const int *)b;
return (x > y) - (x < y); // avoids overflow of x - y
}
int main(void) {
int z[] = {42, 7, 19, 3, 25};
size_t n = sizeof z / sizeof z[0];
qsort(z, n, sizeof z[0], aufsteigend);
for (size_t i = 0; i < n; i++) printf("%d ", z[i]);
printf("\n");
return 0;
}typedef makes function pointers readable. A dispatch table maps names to functions – this lets you build command interpreters or state machines without long if chains:
#include <stdio.h>
typedef int (*BinOp)(int, int);
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; }
struct Befehl { const char *name; BinOp fn; };
int main(void) {
struct Befehl tabelle[] = {{"add", add}, {"sub", sub}, {"mul", mul}};
for (size_t i = 0; i < sizeof tabelle / sizeof tabelle[0]; i++) {
printf("%s(12, 4) = %d\n", tabelle[i].name, tabelle[i].fn(12, 4));
}
return 0;
}WarningThe cast in
qsort comparators must match the real element type. An int comparator on a double array compiles without a warning and sorts nonsense. Never return x - y as the result – it overflows for large values.TipChecking function pointers against
NULL before calling them is a proven pattern for optional callbacks: if (callback) callback(daten);.