Possible Duplicate:
How do you pass a function as a parameter in C?
Suppose I have a function called
void funct2(int a) { } void funct(int a, (void)(*funct2)(int a)) { ; }
what is the proper way to call this function? What do I need to setup to get it to work?
We cannot pass the function as an argument to another function. But we can pass the reference of a function as a parameter by using a function pointer.
A function can take parameters which are just values you supply to the function so that the function can do something utilising those values. These parameters are just like variables except that the values of these variables are defined when we call the function and are not assigned values within the function itself.
Parameters and Arguments Information can be passed to functions as a parameter. Parameters act as variables inside the function. Parameters are specified after the function name, inside the parentheses.
Because functions are objects we can pass them as arguments to other functions. Functions that can accept other functions as arguments are also called higher-order functions. In the example below, a function greet is created which takes a function as an argument.
Normally, for readability's sake, you use a typedef to define the custom type like so:
typedef void (* vFunctionCall)(int args);
when defining this typedef you want the returning argument type for the function prototypes you'll be pointing to, to lead the typedef identifier (in this case the void type) and the prototype arguments to follow it (in this case "int args").
When using this typedef as an argument for another function, you would define your function like so (this typedef can be used almost exactly like any other object type):
void funct(int a, vFunctionCall funct2) { ... }
and then used like a normal function, like so:
funct2(a);
So an entire code example would look like this:
typedef void (* vFunctionCall)(int args); void funct(int a, vFunctionCall funct2) { funct2(a); } void otherFunct(int a) { printf("%i", a); } int main() { funct(2, (vFunctionCall)otherFunct); return 0; }
and would print out:
2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With