double (*f)(double); /* f is a pointer to double function of double argument */The variable
f contains 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) );Interestingly, in the C-language the following phenomena are observed:
double x = sin(1.0); double y = (&sin)(1.0); /* apparently allowed */
Therefore, the following is equally valid,
double (*f)(double); f=sin; /* sin is implicitly converted to &sin */ printf( "%g\n", f(1) ); /* ok to call function pointer */
#include"stdio.h"
#include"math.h"
void print_f_of_1 ( double (*f)(double) ) {
printf("f_of_1=%g\n",f(1)); /* ok to call function pointer */
}
int main(){
print_f_of_1 (&sin);
print_f_of_1 (&cos);
print_f_of_1 (tan); /* ok: function is implicitly converted to function pointer */
return 0;
}
Pointers to functions, like other types of variables, can be elements of arrays,
#include"stdio.h"
#include"math.h"
int main(){
double (*f[3])(double) = {sin,cos,tan};
f[2]=exp;
for(int i=0;i<3;i++)printf("%g\n",f[i](1));
return 0;
}
or members of structures,
#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;
}