#include <stdio.h>
#include <stdlib.h>
void zero(){ printf("zero\n"); };
void one(){ printf("one\n"); };
int main(int argc, char * argv[]){
int i;
void (*jumptable[2])();
jumptable[0] = zero;
jumptable[1] = one;
i = atoi(argv[1]);
jumptable[i]();
return;
};
What does it do? First, it creates an
array of two
function pointers. Then, it assigns values to that array from two functions. Then, it
calls whichever one you specify on the command line. But... why? There are a few reasons. First off, you might have dynamically loaded the functions, so they couldn't be called directly. Second, speed. You could have just used a switch, but suppose you had lots of possibilites, and time mattered. A switch statement takes
O(n) time, because it tests each possibility sequentially. If you put all your code in functions, and put pointers to those functions in an array, the program can lookup the function by index in the array and call it, all in
O(1) time.
But... when would I *really* use a function pointer?
callbacks.