Passing more parameters in C function pointers
architecture, c, pointers
Solution
Ah, if only C supported closures...
Antonio is right; if you need to pass extra parameters, you'll need to redefine your function pointer to accept the additional arguments. If you don't know exactly what parameters you'll need, then you have at least three choices:
- Have the last argument in your prototype be a void*. This gives you flexibility of passing in anything else that you need, but it definitely isn't type-safe.
- Use variadic parameters (...). Given my lack of experience with variadic parameters in C, I'm not sure if you can use this with a function pointer, but this gives even more flexibility than the first solution, albeit still with the lack of type safety.
- Upgrade to C++ and use function objects.
Problem
Let's say I'm creating a chess program. I have a function ``` void foreachMove( void (*action)(chess_move*), chess_game* game); ``` which will call the function pointer action on each valid move. This is all well and good, but what if I need to pass more parameters to the action function? For example: ``` chess_move getNextMove(chess_game* game, int depth){ //for each valid move, determine how good the move is foreachMove(moveHandler, game); } void moveHandler(chess_move* move){ //uh oh, now I need the variables "game" and "depth" from the above function } ``` Redefining the function pointer is not the optimal solution. The foreachMove function is versatile and many different places in the code reference it. It doesn't make sense for each one of those references to have to update their function to include parameters that they don't need. How can I pass extra parameters to a function that I'm calling through a pointer?