Callback functions in C
What is a Callback function?
A function that is passed as an argument to another function(or piece of code) through which it is expected that callback function gets called as part of a certain event. Callbacks are most commonly used in event-driven systems.
Callbacks in C are implemented using function pointers. Similar to a pointer pointing at an address of a variable, a function pointer is a pointer that points to an address of a function. During the execution of a program, a function pointer can be dynamically set to point to different functions.
Given below are the example programs implementing callbacks.
Example1
Example2
We will look into another example in which a C library function makes use of user-supplied callback function.
void qsort (void* arrayPtr, size_t num, size_t size, int (*compare)(const void*,const void*));
C library function qsort()’s fourth parameter accepts user-defined callback function in the form of function pointer. This callback function shall be used by the qsort() library function to compare and sort the objects.
This concludes the blog about callback functions in C. Hope this is helpful.
Thanks and Happy learning!