Passing Pointers to Functions
Learn to use pointers to functions, and also learn how pointers can be used to pass arguments to a function by reference and how that lets us alter variables outside the function's scope.
We'll cover the following...
Pointers to functions
One of the handy things you can do in C, is to use a pointer to point to a function. Then you can pass this function pointer to other functions as an argument, you can store it in a struct, etc. Here is a small example:
#include <stdio.h>int add( int a, int b ) {return a + b;}int subtract( int a, int b ) {return a - b;}int multiply( int a, int b ) {return a * b;}void doMath( int (*fn)(int a, int b), int a, int b ) {int result = fn(a, b);printf("result = %d\n", result);}int main(void) {int a = 2;int b = 3;doMath(add, a, b);doMath(subtract, a, b);doMath(multiply, a, b);return 0;}
Here’s a visualization of the code:
Let’s go through the example above to understand what’s happening.
-
On lines 3–5, 7–9 and 11–13, we define functions
add
,subtract
andmultiply
. These functions return anint
and take twoint
values as input arguments. -
On lines 15–18, we define a function
doMath
which returns nothing (hencevoid
) and which takes three input arguments. The first input argument is:int (*fn)(int a, int b)
This first argument is a ...