CKTIS / C
Callbacks in C: function pointers with `typedef`
Name a function pointer type, then use it to pass strategies and predicates, return a selected function, or store callbacks in structs and arrays for later calls.
Version: ISO C23; implementation support may vary
Syntax
typedef double (*PricingFn)(double);
typedef double PricingFunc(double); /* PricingFunc * is equivalent to PricingFn */
typedef struct Order Order;
typedef int (*OrderPred)(const Order *);
typedef int (*OrderCmp)(const Order *, const Order *);
double add_fee(double);
double double_price(double);
double apply_price(double base, PricingFn fn);
PricingFn select_rule(int use_double);
void apply_rules(PricingFn rules[], size_t n); /* include <stddef.h> for size_t */
typedef struct {
PricingFn price;
} InvoiceProcessor;
/* Inside a function, with add_fee and double_price declared: */
PricingFn fn = add_fee;
PricingFn rules[] = {add_fee, &double_price};
InvoiceProcessor processor = {fn};A typedef callback is a callback whose function pointer type is named with typedef. In typedef double (*PricingFn)(double);, PricingFn aliases a pointer to a function taking one double and returning double. It creates neither a new type nor a function. The parentheses around *PricingFn matter. By contrast, typedef double PricingFunc(double); names the function type; PricingFunc * is equivalent to PricingFn.
In PricingFn fn = add_fee; and when passed as an argument, the function designator add_fee converts to a pointer; &add_fee works too. fn(base) and (*fn)(base) make the same indirect call. A selector can return a PricingFn without calling the selected function. You can later replace the pointer in a variable, or store it in a struct field and call through p->price(base).
PricingFn rules[] can declare an array of function pointers; rules[i](base) calls the function at index i. In a parameter declaration, PricingFn rules[] adjusts to PricingFn *: pass the length separately and stay within bounds. For a dynamic array of n > 0 entries, use PricingFn *items = malloc(n * sizeof *items); from <stdlib.h> after checking that the product fits in size_t. Handle NULL, assign a valid pointer to each slot you use, and call free(items) when done. This frees the array, not the functions.
OrderPred takes one const Order *: zero means false and nonzero means true. Given a valid predicate, count_if calls pred(&orders[i]) once per element. OrderCmp takes two const Order * arguments; a typical comparator contract uses a negative result, zero, or a positive result when the first item is less than, equal to, or greater than the second, respectively.
Call only through an initialized, non-null pointer to a function with compatible parameter and return types. Calling through NULL or through a pointer to an incompatible function type is undefined behavior; a cast does not fix the mismatch. void * is not a portable substitute for a function pointer. These constructs predate ISO C23; support for C23 mode varies by implementation.
Examples
#include <stdio.h>
typedef double (*PricingFn)(double);
typedef struct {
int total;
} Order;
typedef int (*OrderPred)(const Order *);
typedef struct {
PricingFn price;
} InvoiceProcessor;
static double add_fee(double base) { return base + 2.0; }
static double double_price(double base) { return base * 2.0; }
static int is_large(const Order *order) { return order->total >= 10; }
static double apply_price(double base, PricingFn fn)
{
return fn(base); /* Caller must supply a valid callback. */
}
static PricingFn select_rule(int use_double)
{
return use_double ? double_price : add_fee;
}
static size_t count_if(const Order orders[], size_t n, OrderPred pred)
{
size_t matches = 0;
if (pred == NULL)
return 0;
for (size_t i = 0; i < n; ++i)
if (pred(&orders[i]))
++matches;
return matches;
}
int main(void)
{
PricingFn fn = select_rule(0);
printf("strategy: %.0f\n", apply_price(10.0, fn));
PricingFn rules[] = {add_fee, &double_price};
fn = rules[1];
InvoiceProcessor processor = {fn};
const InvoiceProcessor *p = &processor;
printf("switched: %.0f\n", p->price(10.0));
const Order orders[] = {{7}, {10}, {24}};
printf("matches: %zu\n",
count_if(orders, sizeof orders / sizeof orders[0], is_large));
return 0;
}
Result
strategy: 12 switched: 20 matches: 2
`select_rule(0)` chooses `add_fee`. Then `rules[1]` supplies `double_price`, which is called through a struct field. `count_if` finds two matching orders; this example defines a missing (`NULL`) predicate to give a count of zero.
Related lessons
- C · Lesson 39 · Intermediate · Version: 3
- C · Lesson 40 · Intermediate · Version: 3
- C · Lesson 41 · Intermediate · Version: 3
- C · Lesson 42 · Intermediate · Version: 3
- C · Lesson 43 · Intermediate · Version: 3
- C · Lesson 44 · Intermediate · Version: 3
- C · Lesson 45 · Intermediate · Version: 3
- C · Lesson 47 · Intermediate · Version: 3
- C · Lesson 48 · Intermediate · Version: 3