I think the classical example in C is qsort. Quoting from there (and I DO know it's http://www.cplusplus.com, so a not-very-good site, but it seems to be correct)
void qsort ( void * base, size_t num, size_t size, int ( * comparator ) ( const void *, const void * ) );
Function that compares two elements. The function shall follow this prototype:
int comparator ( const void * elem1, const void * elem2 );
The function must accept two parameters that are pointers to elements, type-casted as void*. These parameters should be cast back to some data type and be compared.
The return value of this function should represent whether elem1 is considered less than, equal to, or greater than elem2 by returning, respectively, a negative value, zero or a positive value.
The other "classical" example is the calculator (for example see this, it's C++ but it's the same in C).
You have four math functions, for example
float Plus (float a, float b) { return a+b; }
float Minus (float a, float b) { return a-b; }
float Multiply(float a, float b) { return a*b; }
float Divide (float a, float b) { return a/b; }
in some way you select your operation
/* Here there should be an if or a switch/case that selects the right operation */
float (*ptrFunc)(float, float) = Plus;
and you can call it later (for some reason you don't want to call it directly in the if/switch
, perhaps because you want to make other "things" that are "common" to all the operations, like logging or printing the result)
float result = ptrFunc(1.0f, 2.0f);
Another two things you can use function pointers for are callbacks (as written by vine'th
) and "poor man" virtual functions (you put them in a struct
and when you create the struct
(you know, like using a "poor man" constructor, but this is C so we will call it an initializer), you save there what functions will be used by that struct
).