Open In App
Related Articles

Callbacks in C

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

A callback is any executable code that is passed as an argument to another code, which is expected to call back (execute) the argument at a given time. In simple language, If a reference of a function is passed to another function as an argument to call it, then it will be called a Callback function.

In C, a callback function is a function that is called through a function pointer.

Below is a simple example in C to illustrate the above definition to make it more clear.

C

// A simple C program to demonstrate callback
#include <stdio.h>
 
void A(){
  printf("I am function A\n");
}
 
// callback function
void B(void (*ptr)())
{
    (*ptr)(); // callback to A
}
 
int main()
{
    void (*ptr)() = &A;
 
    // calling function B and passing
    // address of the function A as argument
    B(ptr);
 
    return 0;
}

                    

Output
I am function A

In C++ STL, functors are also used for this purpose.

If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.


Last Updated : 04 Jul, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads