COMP1927 - Function Pointers

Function pointers are a type of argument passed to a function. However the name comes from the fact that you are passing in a pointer to another function.

What this does it let us call a different function depending on the input; e.g.

// math takes in two numbers and an operation.
// it then performs the operation on the two numbers
// E.g. 5, 6, add returns 11
// E.g. 5, 6, multiply returns 30
int math (int a, int b, int (*operation)(int, int)) {
   int result = operation(a, b);

The third parameter in the above code int *(operation)(int, int) is a pointer to a function. It is the address of the function (e.g. the function 'add' would be passed in as &add).

Functions that take or return function pointers are called high order functions.

To pass in a function pointer is as shown above:

returnType funcName (returnType2 (*functionPointerName)(argType1, ..., argTypeN));