Skip to content

Instantly share code, notes, and snippets.

@hosaka
Created August 10, 2015 16:34
Show Gist options
  • Save hosaka/10d76a7e397464f9494b to your computer and use it in GitHub Desktop.
Save hosaka/10d76a7e397464f9494b to your computer and use it in GitHub Desktop.
Jump table example using function pointers in C++
#include <cstdio>
using namespace std;
// function table/jump table example
// various functions that need to be jumped to
void fa() {printf("function a\n");}
void fb() {printf("function b\n");}
void fc() {printf("function c\n");}
void fd() {printf("function d\n");}
// array of function pointers to jump to
void (*functions[])() {fa, fb, fc, fd, nullptr};
// jump function calls the callbacks
int jump(const char *choice)
{
char code = choice[0]; // grab the first character from the input
if (code == 'Q' || code == 'q') return 0;
// count the length of function array
uint func_length = 0;
while (functions[func_length] != nullptr)
{
func_length++;
}
// convert ASCII to int
uint func_no = (int) code -'0';
func_no--; // the array start is zero
// pick the function to run
if (func_no < 0 || func_no >= func_length)
{
printf("invalid choice %d\n", func_no);
return -1;
}
else
{
functions[func_no]();
return 0;
}
}
int main ()
{
void (*fp)() = fa;
// identical to
// void (*fp)() = &func;
printf("in main\n");
fp(); // call from function pointer
// same as calling the pointer explicitly
// (*fp)();
// function table jumps
const int buff_sz = 15; // input buffer size
static char resp[buff_sz]; // user input respone buffer
// read input
fgets(resp, buff_sz, stdin);
// jump to function
(void)jump(resp);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment