Can a function call be stored in a variable?
Let's see if I can explain what I would like to do (sorry for the inacuracy, I'm not a C expert).
I have a set of (similar) functions called depending on some value. Kind of (simplified):
Code:
int Func_0(int i)
{
...
return j;
}
int Func_1(int i)
{
...
return j;
}
...
int Func_n(int i)
{
...
return j;
}
...
for (i=0; i<max_func; ++i)
{
switch (i)
{
case 0:
retval=Func_0(k);
break;
case 1:
retval=Func_1(k);
break;
...
case n:
retval=Func_n(k);
break;
}
// use retval on some code
...
}
The real situation is more complex obviously, but I hope it's clear enough :blush:
Now, I would like to do something like ... (no laughing please! ;))
Code:
FuncType MyFuncs[max_func]; // declare an array of "functions".
MyFuncs[0]=AddressOf(Func_0); // store the function calls
MyFuncs[1]=AddressOf(Func_1);
...
MyFuncs[n]=AddressOf(Func_n);
...
// now use them
for (i=0; i<max_func; ++i)
{
retval=MyFuncs[0](k);
// use retval
...
}
I know most of it is not valid syntax, but I hope the idea is clear.
Is this possible?
Thks
Re: Can a function call be stored in a variable?
What you are looking for is a "function pointer", pleanty of good reference links on on the topic already exist.....
Re: Can a function call be stored in a variable?
You can use a function pointer.
Code:
int answer = 0;
//The functions
int sub(int n1, int n2);
int add(int n1, int n2);
int mult(int n1, int n2);
int div(int n1, int n2);
//The function pointer
int (*func1) (int , int);
//set the function pointer to the address of an arbitrary function
func1 = div;
//divide n1 by n2 with the function pointer and return the result
answer = func1(4,2);
Re: Can a function call be stored in a variable?
Thks a lot. Works fine and saved me a lot of coding. :thumb: