Thursday, March 1, 2012

Call Backs in C

Callback means passing some executable code to a function or in simple words passing a function to a function as a parameter

Example from Wikipedia (in C)


#include <stdio.h>
#include <stdlib.h>
 
/* The calling function takes a single callback as a parameter. */
void PrintTwoNumbers(int (*numberSource)(void)) {
    printf("%d and %d\n", numberSource(), numberSource());
}
 
/* A possible callback */
int overNineThousand(void) {
    return (rand() % 1000) + 9000;
}
 
/* Another possible callback. */
int meaningOfLife(void) {
    return 42;
}
 
/* Here we call PrintTwoNumbers() with three different callbacks. */
int main(void) {
    PrintTwoNumbers(rand);
    PrintTwoNumbers(overNineThousand);
    PrintTwoNumbers(meaningOfLife);
    return 0;
}
This should provide output similar to:
125185 and 89188225
 9084 and 9441
 42 and 42


No comments:

Post a Comment