A general use where pointer to a function is passed as an argument to a function is in qsort
function.
void qsort(void *base, size_t nmemb, size_t size,
int (*compar)(const void *, const void *));
Another use:
Suppose you wanted a program to plot equations. You would give it a range of x
and y
values (perhaps -10
to 10
along each axis), and ask it to plot y = f(x)
over that range (e.g. for -10 <= x <= 10
).
How would you tell it what function to plot? By a function pointer, of course!
The plot function could then step its x
variable over the range you specified, calling the function pointed to by your pointer each time it needed to compute y
. You might call
plot(-10, 10, -10, 10, sin)
to plot a sine
wave, and
plot(-10, 10, -10, 10, sqrt)
to plot the square root function.
But in general, better to avoid using function pointers unless and until it is necessary.