|
-
November 11th, 2008, 12:22 PM
#1
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 
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
Last edited by DeepButi; November 11th, 2008 at 04:34 PM.
Did it help? rate it.
The best conversation I had was over forty million years ago ... and that was with a coffee machine.
-
November 11th, 2008, 12:29 PM
#2
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.....
TheCPUWizard is a registered trademark, all rights reserved. (If this post was helpful, please RATE it!)
2008, 2009,2010
In theory, there is no difference between theory and practice; in practice there is.
* Join the fight, refuse to respond to posts that contain code outside of [code] ... [/code] tags. See here for instructions 
* How NOT to post a question here
* Of course you read this carefully before you posted
* Need homework help? Read this first
-
November 11th, 2008, 12:30 PM
#3
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);
Last edited by ahoodin; November 11th, 2008 at 12:34 PM.
ahoodin
To keep the plot moving, that's why.

-
November 11th, 2008, 04:33 PM
#4
Re: Can a function call be stored in a variable?
Thks a lot. Works fine and saved me a lot of coding.
Did it help? rate it.
The best conversation I had was over forty million years ago ... and that was with a coffee machine.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|