Eroxl's Notes
Function Pointer

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.

Declaration in C

<return-type> (*<var-name>)(<argument-list>);

Example

void ping() {
    printf("ping\n");
}

void foo() {
    void (*aFunc)();    // Declare function pointer
    aFunc = ping;       // Assign function address
    aFunc();            // Call through pointer (calls ping)
}

Applications

Function pointers enable several important programming patterns:

Polymorphism

In C, function pointers can implement polymorphic behavior similar to object-oriented languages:

struct Animal {
    void (*makeSound)(void*);
};

Generic Functions

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]);
}

Callbacks

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));