Created
August 23, 2012 23:17
-
-
Save TikiTDO/3443314 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> | |
// Typedef for functions like "hi" | |
typedef int (*FPN)(int); | |
// Typedef for functions like "bye" | |
typedef int (*sFPN)(int, FPN); | |
// A function that takes an int num, and returns an int (num + 1) | |
int hi(int num) { | |
return num + 1; | |
} | |
// A function that cakes an int num and a callback cb, returns cb(num) + 1 | |
// The callback should be a function that takes an int and returns an int | |
int bye(int num, FPN callback) { | |
return callback(num) + 1; | |
} | |
// Main | |
int main(int argc, char **argv) { | |
// Create a local reference to the function bye, and name it bye_local | |
sFPN bye_local = *bye; | |
// Stores the address of the function hi as a pointer to a void | |
FPN bye_callback = *hi; | |
// Calls bye (Stored in bye_local ) with the callback to hi (stored in bye_callback) | |
printf("hi %d\n", bye_local (1, bye_callback)); | |
return 1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment