ProAnswers.org

How to call a function using function pointer?

1 Like

One of the big uses for function pointers in C is to call a function defined at run-time. For example, the C run-time library has two routines, qsort and bsearch, which take a pointer to a function that it calls to compare two items being sorted; this allows you to sort or search, respectively, anything, based on any criteria you wish to use.
I think the more common use of a function pointer is to generalise function calls. e.g., if there is one function called sum_gen(a, b) which in turn may require to call iself() function or isquare() which are of similar types then what we will do, we will add one function pointer argument to the sum_gen() function like:-
sum_gen(a, b, int (*fun)(void)), where fun can take either the address of iself() function or isquare function.
Now we can call sum_gen() function like:-
sum_gen(a, b, iself) or sum_gen(a, b, isquare). So its basically used to generalise the function calls.

They can be used to create ‘jump table’.
enum { ADD,SUB,MUL,DIV };
double (*fptrs[])(double,double)={ add, sub, mul, divi };
(*fptrs[ operator ] ) (op1,op2);
Jump table might be more efficient and elegant than switch statement.

The other use is, when we want to call some functions sequentially one by one, in that case we declare one array of function pointers initialised to the respective functions like:-
unsigned int i ;
int (*fun[]) (void) = { fun1, fun2, fun3, fun4, fun5, fun6 };
for( i = 0; i < (sizeof (fun) / sizeof (fun[0])); i++)
(*fun [ i ])();
in this way all the function will be called sequentially instead of calling each function one by one.
Note that calling using (*f)() and f() where f is pointer to function is the same in ANSI-C. You might have f()() if f() is a function that returns pointer to function.