Returning pointers to functions from functions
What you'll learn: How to declare a function that hands you a "map" to another specific action.
The "Middleman" Concept
In C, functions are just addresses in memory. We already know functions can return integers or pointers to data. However, in advanced systems—like a plugin architecture or a state machine—you might need a function that decides which specialized tool to give you based on a situation.
Think of a Tool Dispenser. You ask the dispenser for a tool (calling the primary function), and it hands you a specific tool (returning a function pointer). You can then use that tool whenever you like.
Decoding the Syntax
The syntax for this is notoriously "inside-out." To read a declaration that returns a function pointer, start from the variable name and work your way out.
If we want a function named get_operation that returns a pointer to a function taking two ints and returning an int, it looks like this:
int (*get_operation(char op))(int, int) {
// Logic to return a specific function
}
Breaking it down:
get_operation(char op): This is our function name and its parameter.(* ... ): This tells C thatget_operationreturns a pointer.int ( ... )(int, int): This describes the type of function that pointer points to.
Putting it to Work
Let’s look at a concrete example where we choose between an addition or subtraction function.
#include <stdio.h>
int add(int a, int b) { return a + b; }
int sub(int a, int b) { return a - b; }
// A function that returns a pointer to another function
int (*select_action(char type))(int, int) {
if (type == '+') return add;
return sub;
}
int main() {
// 1. Get the function pointer from our "dispenser"
int (*action)(int, int) = select_action('+');
// 2. Use the returned function
int result = action(10, 5);
printf("Result: %d", result); // Outputs 15
return 0;
}
Why use this?
While it looks complex, it decouples your code. The caller doesn't need to know the logic behind which function is chosen; they just call the "dispenser" and execute whatever tool they are handed. This is the foundation of "callbacks" and dynamic dispatch in low-level programming.
Key takeaway
To return a function pointer, wrap the function's name and its parameters in a pointer declaration (*name(args)) surrounded by the return type and parameters of the target function.