Created
January 21, 2012 00:38
-
-
Save mastbaum/1650458 to your computer and use it in GitHub Desktop.
A simple example of function pointers
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
#include <iostream> | |
/** A simple example of function pointers */ | |
// some globally-defined functions that take an int and return an int | |
int foo(int a) { | |
std::cout << "foo: a is " << a << std::endl; | |
return 42; | |
} | |
int bar(int a) { | |
std::cout << "bar: a is " << a << std::endl; | |
return 1337; | |
} | |
int main(int argc, char* argv[]) { | |
// call foo and bar like a normal person | |
int rfoo = foo(3); | |
int rbar = bar(3); | |
// create a pointer to a function that takes an int and returns an int, | |
// and call that pointer "pf" | |
// | |
// the syntax is like declaring a function: | |
// | |
// function: [return type] [function name]([argument type list]) | |
// function pointer: [return type] (*[pointer name])([argument type list]) | |
int (*pf)(int); | |
// make pf point to foo | |
pf = &foo; | |
// call it. wow! | |
(*pf)(12); | |
// now make pf point to bar | |
pf = &bar; | |
// now call that! | |
(*pf)(13); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment