A function pointer is a variable which is used to hold the starting address of a functions and the same can be used to invoke a function. It is also possible to pass address of different functions at different times thus making the function more flexible and abstract.
So the function pointers can be used to simplify code by providing a simple way to select a function to execute based on run-time values. Function pointers do always point to a function having a specific signature. Thus, all functions used with the same function pointer must have the same parameters and return type
Syntax:
ReturnType (*PtrToFun)(arguments if any) |
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | #include "stdio.h" void my_int_func(int x) { printf( "%d\n", x ); } int main() { void (*foo)(int); /* the ampersand is actually optional */ foo = &my_int_func; foo(10); return 0; } |
In above example function pointer foo is used to call the function my_int_func.
Uses of Function Pointers
Pointer to function is useful when you want to choose a function dynamically at run time – usually based on certain conditions. Function Pointers are used to implement generic functions like qsort(), callbacks, state machines and anywhere else run time binding of a function is required. Also Function pointers are used to store interrupt handlers in tables.
To begin, check out the qsort fucntion
void qsort(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *)); |
Here, you need to pass a pointer to the function that compares the objects that you are sorting. Since qsort() is a generic implementation and does not care what you are sorting, it is up to you to implement a funtion which compares the objects that you are sorting and pass it on to qsort(). qsort() just invokes your compare function by dereferencing the function pointer.
nice one