Created
April 9, 2012 14:28
-
-
Save proudlygeek/2343825 to your computer and use it in GitHub Desktop.
C Callbacks
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> | |
| // The original function (adds two number and sets | |
| // the results into the first one | |
| void add(int *x, int *y) | |
| { | |
| *x = *x + *y; | |
| } | |
| void sub(int *x, int *y) | |
| { | |
| *x = *x - *y; | |
| } | |
| // Runs the callback given some parameters. Can also be thinked | |
| // as a "decorator". | |
| // | |
| // TODO: Find a way to pass cb's arguments without polluting | |
| // the main function. | |
| void call_callback(int *a, int *b, void (*cb)(int *, int *)) | |
| { | |
| (*cb)(a, b); | |
| } | |
| int main(int argc, const char *argv[]) | |
| { | |
| int a = 2; | |
| int b = 3; | |
| printf("%d + %d = ", a, b); | |
| call_callback(&a, &b, add); | |
| printf("%d\n", a); | |
| printf("%d - %d = ", a, b); | |
| call_callback(&a, &b, sub); | |
| printf("%d\n", a); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment