Function Pointer Practices

suggest change

Use a typedef When It Improves Readability

A typedef can give a callback signature a concise, descriptive name:

typedef int (*compare_fn)(const void *left, const void *right);

void sort_items(compare_fn compare);

Without the alias, the same parameter is declared directly:

void sort_items(int (*compare)(const void *left, const void *right));

Both declarations accept a pointer to a function that takes two const void * arguments and returns int. Use an alias when it makes an API easier to understand, but avoid hiding pointer semantics when callers need to know that a type is a pointer. This is a design judgment, not an absolute rule; opaque-handle APIs often use pointer aliases deliberately.

Pass Context Explicitly

A callback often needs data in addition to its primary arguments. Passing a caller-supplied context pointer avoids global variables and lets separate callback instances use different state:

typedef double (*surface_fn)(double x, double y, void *context);

double find_minimum(surface_fn function, void *context);

struct cubic_coefficients {
    double x[4];
    double y[4];
};

static double cubic_surface(double x, double y, void *context)
{
    const struct cubic_coefficients *coefficients = context;

    double x_value =
        ((coefficients->x[0] * x + coefficients->x[1]) * x
         + coefficients->x[2]) * x + coefficients->x[3];
    double y_value =
        ((coefficients->y[0] * y + coefficients->y[1]) * y
         + coefficients->y[2]) * y + coefficients->y[3];

    return x_value + y_value;
}

void example(void)
{
    struct cubic_coefficients coefficients = {
        .x = {1.0, 2.0, 3.0, 4.0},
        .y = {5.0, 6.0, 7.0, 8.0},
    };

    double minimum = find_minimum(cubic_surface, &coefficients);
    (void)minimum;
}

The callback must know the actual type of the object supplied through context. Document that contract, including whether NULL is allowed and how long the pointed-to object must remain alive.

Not every callback needs context. For a stateless operation, a simpler signature may be clearer. When designing a reusable callback API, however, a context parameter is usually inexpensive and makes the interface more flexible.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents