How to use callback function in C

2 Answers

0 votes
#include <stdio.h>

/*
A callback function is any function that receives 
a reference of another function as the argument 
to call the function
*/

void aFunction() {
    printf("aFunction() called from callBackFunction\n");
}


void callBackFunction(void (*Fptr)()) {
    (*Fptr) ();
}


int main()
{
    void (*Fptr)() = &aFunction;
    
    callBackFunction(Fptr);
    
    return 0;
}

  
  
/*
run:
  
aFunction() called from callBackFunction
 
*/
    

 



answered Jun 5, 2024 by avibootz
edited Jul 4, 2024 by avibootz
0 votes
#include <stdio.h>

void callback(void *x) {
    int n = *(int*)x;
    
    printf("callback n = %d\n", n);
}

void afunction(void (*fp)(void*), int x) {
    printf("afunction x = %d\n", x);
  
    fp(&x);
}

int main(void) {
    afunction(callback, 123);
  
    return 0;
}

 
         
/*
run:
      
afunction x = 123
callback n = 123
     
*/

 



answered Jul 4, 2024 by avibootz
...