When do you use function pointers in C?

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.

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.

Improve Answer Discuss the question "When do you use function pointers in C?" Watch Question

First answer by Joe Sewell. Last edit by Ratneshp. Contributor trust: 14 [recommend contributor]. Question popularity: 9 [recommend question]

Research your answer:

Answers.com > Wiki Answers > Categories > Technology > Computers > Computer Programming > When do you use function pointers in C?

Our contributors said this page should be displayed for the questions below. (Where do these come from)
If any of these are not a genuine rephrasing of the question, please help out and edit these alternates.
Pointers to function?  When o use function pointers?  When to use function pointers?  Advantage of function pointers?  Where you use function pointers in c?  What is the real use of function pointers?  In what circumstances do you use function pointers in C?