...

/

Passing Pointers to Functions

Passing Pointers to Functions

Learn to use pointers to functions, 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:

C
#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:

Variables declared in main are allocated on the stack before it is invoked
1 / 24
Variables declared in main are allocated on the stack before it is invoked

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, and multiply. These functions return an int and take two int values as input arguments.

  • On lines 15–18, we define a function doMath which returns nothing (therefore void) and which takes three input arguments. The first input argument is:

    int (*fn)(int a, int b)
    

    This first argument is a pointer to a ...