double (*f)(double);Now
f
is a variable containing a pointer to a function
that takes one double argument and returns a double result.
One can assign a value to this variable and then use it as a normal
function, for example, after #include"math.h"
,
f=sin; printf( "%g\n", f(1) );
#include"stdio.h" #include"math.h" void print_f_of_1 ( double (*f)(double) ) { printf("f_of_1=%g\n",f(1)); } int main(){ print_f_of_1 (sin); print_f_of_1 (cos); print_f_of_1 (tan); return 0; }
Pointers to functions, like other types of variables, can be elements of arrays, for example,
#include"stdio.h" #include"math.h" int main(){ double (*f[3])(double) = {sin,cos,tan}; for(int i=0;i<3;i++)printf("%g\n",f[i](1)); return 0; }or members of structures, for example,
#include"stdio.h" #include"math.h" struct funs {double (*a) (double); double (*b) (double);}; int main(){ struct funs F = {.a=sin,.b=cos}; printf("%g %g\n",F.a(1),F.b(1)); return 0; }