Learn C · lesson 59 of 60 · about 10 minutes
Function Pointers
Store a function in a variable, keep functions in an array, and pass them to other functions.
What you'll learn
- Declare a pointer to a function
- Call a function through a pointer
- Pass a function to another function
Which server is busiest?
The traffic grid can answer "which server is busiest?" in more than one way: the most requests in the whole day, the highest single quarter, or the busiest even in its quietest quarter. The report reads the measure to use, total, peak or low, one per line until end, and names the top server: By total: web (320). The load check already has total_load and peak_load, so one function that takes the measure as a function pointer can do all three.
Functions have addresses too
A function lives somewhere in memory, so you can point at it. int (*op)(int, int); declares op, a pointer to any function that takes two ints and returns an int.
Assign it a function's name, op = add;, and call it like the function itself: op(2, 3).
Choosing a function at run time
#include <stdio.h>
int add(int a, int b) { return a + b; }
int mul(int a, int b) { return a * b; }
int main(void) {
int (*op)(int, int) = add;
printf("%d\n", op(4, 5));
op = mul;
printf("%d\n", op(4, 5));
return 0;
}Output
9
20Passing functions around
A function can take another function as a parameter. That's how qsort, from the capstone, works: you hand it a compare function and it calls it whenever it needs to compare two items. A typedef gives the pointer type a short name.
Apply a function to every item
#include <stdio.h>
typedef int (*Transform)(int);
int twice(int x) { return x * 2; }
int square(int x) { return x * x; }
void apply(int a[], int n, Transform f) {
for (int i = 0; i < n; i++) a[i] = f(a[i]);
}
int main(void) {
int a[] = {1, 2, 3};
apply(a, 3, twice);
apply(a, 3, square);
printf("%d %d %d\n", a[0], a[1], a[2]);
return 0;
}Output
4 16 36One loop, any measure
top_server takes int (*measure)(const int[], int), a pointer to any function that gets a row of readings and gives back a number. It calls measure(g[r], 4) for each server and keeps the highest, the first one if two tie. main points measure at total_load, peak_load or the new low_load, depending on the word typed, and an unknown word leaves it NULL: No measure called busiest.
Tip
The brackets in int (*op)(int, int) matter. Without them, int *op(int, int) declares a function that returns a pointer.
Now try it yourself
This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.