Function Pointers and Dispatch Tables

001  int add(int a, int b);
002  int example(int (*f) (int, int), int a, int b);
003  
004  typedef int (*fn_ptr_int_int) (int, int);
005  
006  int main(int argc, char *argv[])
007  {
008      // directly declare a variable for use
009      int (*fn_ptr)(int, int);
010      fn_ptr = add;
011  
012      int c = fn_ptr(5, 6);
013  
014      // typedefs are commonly used to make these more readable
015      // actually bad practice however
016      fn_ptr_int_int d = &add;
017      c = d(5, 6);
018  
019      // using functions with function pointer parameters
020      c = example(add, 5, 6);
021  }
022  
023  int add(int a, int b)
024  {
025      return a + b;
026  }
027  
028  int example(int (*f) (int, int), int a, int b)
029  {
030      return f(a, b);
031  }

Dispatch Tables

An alternative to switch statements where an index is used to select a function from a set of functions with equal return type and paramenters.

001  void (*pattern[PATTERN_MAX]) (struct data *data) = { pattern1, pattern2, pattern3, pattern4, ... }; 
002  
003  int main(int argc, char *argv[])
004  {
005      // Assuming an array of objects with a designated pattern each,
006      // call the respective pattern function for each object
007  
008      for (int i = 0; i < N; i++) {
009          pattern[obj[i].pattern](&obj[i]);
010      }
011  }