Computer >> Computer tutorials >  >> Programming >> C programming

Callback function in C


The callback is basically any executable code that is passed as an argument to other code, that is expected to call back or execute the argument at a given time. We can define it in other words like this: If the reference of a function is passed to another function argument for calling, then it is called the callback function.

In C we have to use the function pointer to call the callback function. The following code is showing how the callback function is doing its task.

Example Code

#include<stdio.h>
void my_function() {
   printf("This is a normal function.");
}
void my_callback_function(void (*ptr)()) {
   printf("This is callback function.\n");
   (*ptr)();    //calling the callback function
}
main() {
   void (*ptr)() = &my_function;
   my_callback_function(ptr);
}

Output

This is callback function.
This is a normal function.