Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 135 ยท Functions

Function Pointers

Master C function pointers - declaring and calling them, typedefs that make them readable, callbacks with context, dispatch tables, and qsort comparators.

A function in C lives at an address in memory, just like a variable does. A function pointer stores that address, which lets you treat a function as a value: keep it in a variable, pass it to another function, store it in an array or a struct, and call it later. That one idea powers callbacks, plug-in systems, event handlers, state machines and the standard library's qsort.

The syntax is famously awkward the first time you see it, so this lesson goes slowly. You'll learn to read and write function pointer types, make them readable with typedef, write functions that accept callbacks, build a dispatch table that replaces a long switch, and write correct comparison functions for qsort.

Declaring and calling a function pointer

Start with an ordinary function:

C
int add(int a, int b);

A pointer to it is declared by writing the same thing with (*name) in place of the function name:

C
int (*operation)(int, int);

Read it from the name outward: operation is a pointer (*) to a function taking (int, int) and returning int. The parentheses around *operation are essential. Without them, int *operation(int, int); declares a function returning int *, which is something else entirely.

C Assigning and calling a function pointer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

It prints add: 13, multiply: 42, explicit: 42, points to multiply? yes and no operation set.

Three conveniences make function pointers easier than they look:

  • A function name decays to a pointer in most expressions, the same way an array name does. operation = add; and operation = &add; mean the same thing.
  • You call through a pointer like a function. operation(6, 7) and (*operation)(6, 7) are identical. Most modern code uses the shorter form; older code often writes the * to make it obvious a pointer is involved.
  • Function pointers can be compared and set to NULL. Calling a null function pointer is undefined behavior (in practice, a crash), so check optional callbacks before calling them.

The pointer's type must match the function's type exactly: same return type, same parameter types. Calling a function through a pointer of a different type is undefined behavior, even if the program seems to work. GCC warns with -Wincompatible-pointer-types (an error by default since GCC 14) when you assign a mismatched function.

Making it readable with typedef

Function pointer types get hard to read quickly, especially as parameters or return types. A typedef gives the type a name. There are two common styles:

C
// Style 1: name the pointer type
typedef int (*binary_op_fn)(int, int);
binary_op_fn op = add;

// Style 2: name the function type, and write the * where you use it
typedef int binary_op(int, int);
binary_op *op2 = add;

Style 2 is gaining popularity because the * stays visible at the point of use, so readers can see it's a pointer. Both produce the same type. Compare how a function that returns a function pointer looks with and without a typedef:

C
// Without typedef: pick_operation takes a char and returns a pointer
// to a function taking (int, int) and returning int.
int (*pick_operation(char symbol))(int, int);

// With typedef: the same declaration
binary_op *pick_operation(char symbol);

C23 also lets you write typeof(add) *op3 = add; to get "pointer to a function with the same type as add" without spelling it out.

When you meet a complicated declaration in someone else's code, use the inside-out rule: start at the name, read right while you can ((...) = "function taking", [n] = "array of"), then read left (* = "pointer to"), and jump out of each pair of parentheses. void (*handlers[4])(int) reads: handlers is an array of 4 pointers to functions taking int and returning void.

Callbacks

A callback is a function you pass to another function so it can call back into your code. The receiving function knows when to do something; the callback decides what. Here a generic transform function applies any operation to every element of an array:

C A transform function that takes a callback

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The output:

TEXT
squared  9 64 1 81 16
+10      19 74 11 91 26
clamped  19 50 11 50 26
2 values were clamped

Notice the extra void *context parameter. Without it, a callback could only work with its own argument and global variables. With it, the caller passes a pointer to any data it likes (an offset, a counter, a whole struct), and the callback converts it back to the right type. This "function pointer + void * user data" pair is the standard C callback pattern; you'll see it in threading libraries, GUI toolkits and event loops. void Pointers and Generic Code explains void * in depth.

Arrays of function pointers: dispatch tables

A long switch that calls a different function for each case can often be replaced by a table: an array (or array of structs) holding function pointers. Adding a new operation then means adding a row, not editing logic.

This calculator reads lines like 12 + 5 from the Input box and finds the right function by looking up the operator symbol in a table:

C A calculator with a dispatch table

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

With the preset input it prints:

TEXT
12 + 5 = 17
7 * 6 = 42
2 ^ 10 = 1024
9 / 0: not allowed
8 % 3: unknown operator
100 / 7 = 14

Try adding a % row: write an op_mod function and one table entry, and the calculator supports it. Nothing else changes. find_operator returns binary_op *, a function pointer, or NULL when the symbol isn't in the table, and the caller checks for NULL before calling. The table is static const, so it lives in read-only memory and can't be changed by accident.

The same structure appears in interpreters (one handler per opcode), menu systems (one handler per menu item), command-line tools (one function per subcommand) and state machines (one function per state).

qsort and comparison functions

The standard library's qsort (in <stdlib.h>) sorts an array of any type. It can do that because you give it a comparison function through a function pointer:

C
void qsort(void *base, size_t count, size_t size,
           int (*compare)(const void *a, const void *b));

qsort calls compare with pointers to two elements. Your function must return a negative number if the first should come before the second, zero if they're equal, and a positive number if the first should come after. Inside, you convert the const void * pointers back to the real element type.

C Sorting with qsort comparators

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The output:

TEXT
-2147483647 -7 0 19 19 42 2147483647 
2147483647 42 19 19 0 -7 -2147483647 
fig date kiwi pear apple banana 

Two details professionals watch for:

  • Don't compare ints with return x - y;. It looks clever, but 2147483647 - (-2147483647) overflows int, which is undefined behavior and in practice gives a wrong sign, so the sort silently breaks. (x > y) - (x < y) produces -1, 0 or 1 safely. The array above includes extreme values to prove it.
  • Know what the element pointer points to. When you sort an array of const char *, each element is a pointer, so qsort hands you a pointer to a pointer. Casting a straight to const char * is a classic bug that compiles fine and compares garbage.

qsort isn't guaranteed to be stable: equal elements may end up in any order. If you need a stable order, add a tie-breaker to the comparison (as the word example does with strcmp). The qsort and bsearch lesson covers sorting structs by several keys and searching sorted arrays with bsearch.

Function pointers in structs

Storing function pointers inside a struct groups data with the operations that work on it. It's how C code builds "interfaces": a set of operations that different implementations can fill in.

C
typedef struct {
    const char *name;
    double (*area)(const void *shape);
    void (*describe)(const void *shape);
} shape_ops;

A circle and a rectangle could each provide their own shape_ops, and code that draws shapes would call ops->area(shape) without knowing which kind it has. Operating systems use exactly this pattern for device drivers and file systems. You'll build structs like this after the Structures lessons.

Pitfalls and rules

  • Match the type exactly. Don't cast a function to a different function pointer type and call it. A comparison function for qsort must take const void * parameters, not const int *.
  • Function pointers and void * are different. The C standard doesn't allow converting between function pointers and void * (POSIX systems do, which is how dlsym works). To store "any function", use a specific function pointer type and cast back to the original type before calling.
  • Check optional callbacks for NULL before calling them.
  • Use a typedef as soon as a function pointer type appears more than once.
  • Pass a void *context with every callback you design, so callers aren't forced to use globals.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does double (*convert)(double); declare?

    The parentheses group * with the name, so convert is a pointer; the (double) after it says it points to a function taking a double, and the leading double is the return type.
  2. 2. Given int (*op)(int, int) = add;, which call is NOT valid?

    Calling through the pointer works with or without dereferences (each * just gives back a function designator, which decays again). op is not an array, so op[1] is meaningless here.
  3. 3. Why is return x - y; a bad comparison function for qsort on int values?

    For values like 2147483647 and -2147483647 the difference doesn't fit in an int. Use (x > y) - (x < y) or explicit comparisons instead.
  4. 4. You sort const char *names[] with qsort. What do the comparator's const void * arguments point to?

    qsort always passes pointers to elements. Each element is a pointer, so you must convert to a pointer-to-pointer and dereference once to get the strings.
  5. 5. In the callback pattern map(value, context), what is the void *context parameter for?

    The caller passes a pointer to whatever data it wants (an offset, a counter, a struct); the callback converts it back to the right type.

Summary

  • A function pointer holds the address of a function: int (*op)(int, int) = add;, then call it with op(2, 3).
  • Function names decay to pointers; & and * are optional when assigning and calling.
  • The pointer type must match the function's type exactly; calling through a mismatched type is undefined behavior.
  • Use typedef (typedef int binary_op(int, int); then binary_op *op) to keep declarations readable.
  • Callbacks let a function delegate work to caller-supplied code; pair them with a void *context.
  • Arrays or tables of function pointers replace long switch statements and make adding cases easy.
  • qsort takes a comparator returning negative, zero or positive; avoid x - y overflow and dereference element pointers correctly.

Next: Arrays, where you'll store many values of the same type side by side.