Skip to content

Instantly share code, notes, and snippets.

@tkellen
Created June 7, 2012 13:28
Show Gist options
  • Save tkellen/2888811 to your computer and use it in GitHub Desktop.
Save tkellen/2888811 to your computer and use it in GitHub Desktop.
function pointer in c
// this code will run mode_one once, then mode_two forever.
#include <stdio.h>
// a pointer to the mode you want to call
void (*modePtr)();
// function prototypes
void mode_one();
void mode_two();
// modes
void mode_one(void)
{
printf("running mode one");
// change mode pointer to a different function
modePtr = mode_two;
}
void mode_two(void)
{
printf("running mode two");
}
void main(void)
{
// set mode pointer to mode one
mode_pointer = mode_one;
while(1)
{
// run whatever function the mode pointer is currently pointing to
modePtr();
}
}
// so, anywhere you have stuff like mode = ENTERING_LOCKOUT you'll change it to
// mode = entering_lockout_mode (the function that actually gets called as a result)
// instead of setting the mode to a number that the mainline has to run through a
// switch statement to find a function for, you're setting the mode to the function itself
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment