Created
February 15, 2022 11:11
-
-
Save nadar71/c0cf799856a2464d9126fef27cda5ece to your computer and use it in GitHub Desktop.
C callback sample without parameters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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