Created
August 25, 2015 16:04
-
-
Save CarlLee/bef2ded975b24303ba1e to your computer and use it in GitHub Desktop.
Demonstration of "callback function" in C
This file contains 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
void *(mouse_listener)(int, int); | |
// Print coordinates if mouse is clicked | |
void on_mouse_clicked(int x, int y){ | |
printf("%d, %d", x, y); | |
} | |
// Tell other code what to do when mouse is clicked by registering a event listener | |
void register_mouse_listener(void *(func_pointer)(int, int)){ | |
mouse_listener = func_pointer; | |
} | |
// The actual code that does mouse click (usually this is done elsewhere by other code, | |
// but we can simulate the functionality here) | |
void click_mouse(int x, int y){ | |
do_something(); | |
if(NULL != mouse_listener) | |
(*mouse_listener)(x, y); | |
} | |
int main(){ | |
register_mouse_listener(on_mouse_clicked); | |
click_mouse(100, 200); | |
// on_mouse_clicked will be called; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment