How to use a function as an argument in a function?
Andrea 'Fyre Wyzard' Bocci
fwyzard@inwind.it
Sat Feb 9 06:09:00 GMT 2002
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
More information about the Gcc-help
mailing list