Search⌘ K
AI Features

Passing Pointers to Functions

Explore how to use pointers to functions in C, enabling you to pass functions as arguments and modify data effectively. Learn the key differences between passing by value and passing by reference through pointers, enhancing your ability to write efficient and flexible C programs.

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 ...