A function pointer is a variable that stores the address of a procedure. Function pointers enable dynamic control flow by allowing the target of a procedure call to be determined at runtime.
<return-type> (*<var-name>)(<argument-list>);
void ping() {
printf("ping\n");
}
void foo() {
void (*aFunc)(); // Declare function pointer
aFunc = ping; // Assign function address
aFunc(); // Call through pointer (calls ping)
}
Function pointers enable several important programming patterns:
In C, function pointers can implement polymorphic behavior similar to object-oriented languages:
struct Animal {
void (*makeSound)(void*);
};
Function pointers allow writing generic functions that can perform arbitrary operations:
void map(int (*fn)(int, int), int n, int *a, int *b, int *result) {
for (int i = 0; i < n; i++)
result[i] = fn(a[i], b[i]);
}
Function pointers enable event-driven programming by registering handlers to be called later:
void diskRead(char* buf, int blockNum, int numBytes,
void (*whenComplete)(char*, int, int));