liveBook · Manning

Function pointer type

As explained in Modern C, Third Edition

A function pointer is a C pointer value that designates a function and can be used to invoke or pass that function indirectly.

A function pointer is a pointer value that designates a function. A function name used without following parentheses undergoes function decay: it becomes a pointer to the function's start and can be passed or invoked indirectly. section 11.4

typedef void atexit_function(void);
// Two equivalent definitions of the same type, which hides a pointer
typedef atexit_function* atexit_function_pointer;
typedef void (*atexit_function_pointer)(void);
// Five equivalent declarations for the same function
void atexit(void f(void));
void atexit(void (*f)(void));
void atexit(atexit_function f);
void atexit(atexit_function* f);
void atexit(atexit_function_pointer f);

Compare equivalent declarations for a callback type and for a function parameter; typedefs can make pointer syntax easier to read. section 11.4

Calling through a function designator

For double f(double), the calls f(3), (&f)(3), (*f)(3), (*&f)(3), and (&*f)(3) are equivalent. Their abstract steps differ—decay, address-of, dereference, and call—but each invokes f. section 11.4

Function pointers make algorithms depend on another function. The comparison parameter of qsort and bsearch lets one generic operation handle arrays of different element types, provided the element size and comparison function agree. section 18.1.5 section 11.4

Keep these constraints explicit:

  • Match function pointer types exactly when assigning or calling them. section 11.5
  • Write comparison functions that return a strictly negative, positive, or zero result; subtracting integers can overflow. section 11.4
  • Use a callback interface to select behavior at runtime, as with configurable logging or thread start functions. section 11.4 section 20.0

How Modern C, Third Edition covers it

How deep it goes
Explains decay, declaration syntax, equivalent calls, callback contracts, and exact matching, while stopping short of broader pointer internals.
Examples
Uses equivalent call expressions, qsort and bsearch comparison functions, configurable loggers, and thrd_create callbacks.
What it assumes
Assumes familiarity with C declarations and pointers while introducing function decay and function-pointer declaration forms.
What you can do after
Build callback-based C interfaces and apply qsort, bsearch, logging, or thread creation with correctly matched function types.
How it connects
Connects function pointers with function decay, typedefs, callbacks, qsort, bsearch, type-generic programming, and threads.

Also explained in

Compare how 4 books explain function pointer type →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern C, Third Edition. The section links point to the parts of the book it draws on.