Skip to content

Instantly share code, notes, and snippets.

@nadar71
Created February 15, 2022 11:11
Show Gist options
  • Save nadar71/c0cf799856a2464d9126fef27cda5ece to your computer and use it in GitHub Desktop.
Save nadar71/c0cf799856a2464d9126fef27cda5ece to your computer and use it in GitHub Desktop.
C callback sample without parameters
#include <stdio.h>
#include <stdlib.h>
/* The calling function takes a single callback as a parameter. */
void PrintTwoNumbers(int (*numberSource)(void)) {
int val1 = numberSource();
int val2 = numberSource();
printf("%d and %d\n", val1, val2);
}
/* A possible callback */
int overNineThousand(void) {
return (rand()%1000) + 9001;
}
/* Another possible callback. */
int meaningOfLife(void) {
return 42;
}
/* Here we call PrintTwoNumbers() with three different callbacks. */
int main(void) {
time_t t;
srand((unsigned)time(&t)); // Init seed for random function
PrintTwoNumbers(&rand);
PrintTwoNumbers(&overNineThousand);
PrintTwoNumbers(&meaningOfLife);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment