Skills101

AdvancedC Programming · Lesson 14 of 15 · Updated ·

Function Pointers in C — Callbacks, qsort and Arrays of Functions

A variable has an address, and so does a function: its machine code sits somewhere in the code (text) segment of memory. A function pointer stores that address, so you can decide at run time which function to call. This is how qsort sorts any kind of data, how menus and event handlers are written, and how C imitates some of what C++ does with virtual functions.

1. Declaring and calling a function pointer

Take a normal function:

int add(int a, int b) { return a + b; }

A pointer that can hold add must have the same return type and parameter types:

int (*op)(int, int);     /* op: pointer to a function taking (int, int) and returning int */

The brackets around *op are essential. Without them, int *op(int, int); declares a function named op that returns int * — a completely different thing.

#include <stdio.h>

int add(int a, int b) { return a + b; }
int sub(int a, int b) { return a - b; }

int main(void) {
    int (*op)(int, int);
    op = add;                     /* a function name gives its address */
    printf("%d\n", op(10, 4));
    op = sub;                     /* point to another function */
    printf("%d\n", (*op)(10, 4)); /* the older calling style, same meaning */
    return 0;
}
14
6
  • op = add; and op = &add; mean the same thing.
  • op(10, 4) and (*op)(10, 4) mean the same thing.

The pointer op holds the address of a function in the code segment; first it points to add and op(10, 4) gives 14, then it is changed to point to sub and gives 6

2. typedef makes them readable

Function pointer syntax gets hard to read quickly. A typedef gives the type a short name:

typedef int (*BinaryOp)(int, int);   /* BinaryOp = pointer to int f(int, int) */

BinaryOp op = add;

Now BinaryOp can be used like any other type — for variables, parameters and arrays.

3. Callbacks: passing a function to a function

A callback is a function you pass to another function, which "calls it back" when needed. The receiving function does not need to know which function it got — it only needs the signature.

Example: a shop applies different discount rules to the same list of prices.

#include <stdio.h>

typedef int (*Rule)(int);

int festival(int price) { return price - price / 10; }      /* 10% off */
int flat50(int price)   { return price > 500 ? price - 50 : price; }

void apply(int prices[], int n, Rule rule) {
    for (int i = 0; i < n; i++)
        printf("%d ", rule(prices[i]));          /* call back the rule */
    printf("\n");
}

int main(void) {
    int prices[] = {200, 800, 1500};
    apply(prices, 3, festival);
    apply(prices, 3, flat50);
    return 0;
}
180 720 1350
200 750 1450

apply was written once; new rules can be added later without changing it. This idea — "the caller decides the behaviour" — is the core of callbacks.

4. qsort: the standard library's callback

qsort in <stdlib.h> can sort any array: ints, doubles, strings, structures. It does not know your data type, so you give it a comparator function:

void qsort(void *base, size_t count, size_t size,
           int (*compar)(const void *, const void *));

The comparator receives two void * pointers to elements and must return:

  • a negative number if the first should come before the second,
  • 0 if they are equal,
  • a positive number if the first should come after.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct student { char name[10]; int marks; };

int by_marks_desc(const void *a, const void *b) {
    const struct student *x = a, *y = b;
    return (y->marks > x->marks) - (y->marks < x->marks);   /* higher marks first */
}

int by_name(const void *a, const void *b) {
    const struct student *x = a, *y = b;
    return strcmp(x->name, y->name);
}

int main(void) {
    struct student s[] = {{"Ravi", 72}, {"Anu", 91}, {"Meera", 85}, {"Kabir", 60}};
    int n = sizeof(s) / sizeof(s[0]);

    qsort(s, n, sizeof(s[0]), by_marks_desc);
    for (int i = 0; i < n; i++) printf("%s:%d ", s[i].name, s[i].marks);
    printf("\n");

    qsort(s, n, sizeof(s[0]), by_name);
    for (int i = 0; i < n; i++) printf("%s ", s[i].name);
    printf("\n");
    return 0;
}
Anu:91 Meera:85 Ravi:72 Kabir:60
Anu Kabir Meera Ravi

Why not just return y->marks - x->marks;? For marks it works, but for large ints the subtraction can overflow and give the wrong sign. The pattern (a > b) - (a < b) always gives -1, 0 or 1 safely.

5. An array of function pointers: a menu

Instead of a long switch, keep the functions in an array and pick one by index. This is how simple calculators, command interpreters and state machines are often built.

An array ops of four function pointers; index 0 points to add, 1 to sub, 2 to mul and 3 to divide, so calling entry 2 with 6 and 3 runs mul and gives 18

#include <stdio.h>

int add(int a, int b) { return a + b; }
int sub(int a, int b) { return a - b; }
int mul(int a, int b) { return a * b; }
int dvd(int a, int b) { return b ? a / b : 0; }

int main(void) {
    int (*ops[4])(int, int) = {add, sub, mul, dvd};
    const char *names = "+-*/";
    int choice;
    scanf("%d", &choice);              // Input: 2
    if (choice >= 0 && choice < 4)
        printf("6 %c 3 = %d\n", names[choice], ops[choice](6, 3));
    for (int i = 0; i < 4; i++)
        printf("%d ", ops[i](6, 3));
    printf("\n");
    return 0;
}
6 * 3 = 18
9 3 18 2

Here the user typed 2, so ops[2] — mul — was called. Always check the index before calling through the array — calling ops[7] jumps to a random address.

6. Where you will meet them

UseExample
Sorting and searching any typeqsort, bsearch
Event handlers"call this function when the button is pressed"
Plugins and driversa table of functions (open, read, write) per device, as in the Linux kernel
atexitregister a function to run when the program ends
Signal handlingsignal(SIGINT, handler)

Common mistakes

  • Forgetting the brackets: int *f(int); is a function returning a pointer, not a pointer to a function.
  • Assigning a function with a different signature (for example double f(int) to int (*)(int)). Calling through the wrong type is undefined behaviour.
  • Writing op = add(); — that calls add and stores its result. Use op = add;.
  • A qsort comparator that returns only 0 or 1 (like return a > b;) — it must also return negative values.
  • Calling through a NULL or uninitialised function pointer.

Quick recap

  • int (*p)(int, int) is a pointer to a function taking two ints and returning int.
  • A function name gives its address; p(x, y) calls through the pointer.
  • typedef turns the syntax into a readable type name.
  • Callbacks let the caller choose behaviour; qsort uses a comparator returning negative, 0 or positive.
  • An array of function pointers replaces a long switch; always check the index.

Practice what you learned

📝 Quiz: Function Pointers in C5 questions · instant answers & explanations · +10 XP · counts towards your free certificateTake the quiz →