Skip to content

Instantly share code, notes, and snippets.

@mastbaum
Created January 21, 2012 00:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mastbaum/1650458 to your computer and use it in GitHub Desktop.
Save mastbaum/1650458 to your computer and use it in GitHub Desktop.
A simple example of function pointers
#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