This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Re: How to use a function as an argument in a function?
- From: Andrea 'Fyre Wyzard' Bocci <fwyzard at inwind dot it>
- To: daniel_usikov at agilent dot com,gcc-help at gcc dot gnu dot org
- Cc: daniel_usikov at agilent dot com
- Date: Sat, 09 Feb 2002 11:20:27 +0100
- Subject: Re: How to use a function as an argument in a function?
At 18.49 08/02/2002 (GMT -0800), daniel_usikov@agilent.com wrote:
>In C (or C++) I need to transfer a function name to another function, like
>
>double fun(double x){
>return x;
>}
>
>double calc(double FF(double x)){
> return a=fun(1.0);
>}
>
>print (calc(fun));
>
>How can I do it?
You pass a pointer to the function:
/* test for passing functions as args */
double fun1 (double x) {
return x;
}
double fun2 (double x) {
return x*x;
}
double calc (double (*fun) (double)) {
return fun(2.0);
}
int main (int argc, char **argv) {
printf ("fun1(2.0): %f\n", calc (fun1));
printf ("fun2(2.0): %f\n", calc (fun2));
return 0;
}
/* end of test */
It may be more convenient to define the appropriate type:
typedef double (*pFunction) (double);
and then use
double calc (pFunction fun) {
...
>With regards
>Daniel
Is this what you were after ?
HTH
fwyzard