This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

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



Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]