Skip to main content

Section 29.1 Function Pointers

Just like int *p; declares p as a pointer to an int, we can declare a pointer to a function. The syntax looks a little unusual at first:
void (*functionptr)(int);
This declares functionptr as a pointer to a function that takes a single int argument and returns nothing (void). Just like arrays, function names themselves act as addresses, so both of the following work to assign a function pointer:
functionptr = &printNumber;   /* explicit address-of */
functionptr = printNumber;    /* implicit conversion, same effect */
To actually call the function through the pointer, we dereference it (though C is forgiving here, and functionptr(x) works too):
(*functionptr)(my_number);
Let’s see this in action:
A function pointer can be reassigned to point to a different function at any time, as long as that function has a matching prototype (same return type and same parameter types). This is exactly what lets us pick a function based on user input, rather than hard-coding an if/else that calls one function or the other directly:
Time to practice!

Activity 29.1.

Define two functions, float square(float x) and float cube(float x). Ask the user to enter a number and choose whether they want to square (2) or cube (3) it. Declare a function pointer, and use an if/else statement to assign it to the correct function based on the user’s choice. Finally, use your function pointer to calculate and print the result.

Activity 29.2.

Let’s use a function pointer to convert a whole batch of temperatures! We have two functions, float cTof(float c) and float fToc(float f). Ask the user which conversion they want to do (1 for Celsius→Fahrenheit, 2 for Fahrenheit→Celsius), declare a function pointer, and assign it to the correct function based on the user’s choice. Then write a for loop that iterates through the temperature array, passing each value to your function pointer and printing the result.