Why to use function pointer? [duplicate]

Some more things function pointers are often used for:

  • Runtime polymorphism: You can define a structure that encapsulates a function pointer, or a pointer to a function table. This enables you to call the specified function at runtime, even for a type of client object that did not exist when your library was written. You can use this to implement multiple dispatch or something like the visitor design pattern in C. This is also how C++ classes and their virtual member functions were originally implemented under the hood.
  • Closures: These can be structures containing a function pointer and one or more of its arguments.
  • State Machines: Instead of a switch with a case for each state label, I’ve often found it convenient to give the handler for each state its own function. The current state is the function you’re in, the state transitions are tail-recursive calls, and the program variables are parameters. The state labels then become function pointers, which you might store in a table or return from a function.
  • Higher-Order Functions: Two examples from the C standard library are qsort() and btree(), which generalize the type of elements and the comparison function.
  • Low-Level Support: Shared-library loaders, for example, need this.

Leave a Comment