8.3 Pointer of function

A pointer to function allows a program to call functions indirectly. This is an extremely useful feature in pure C programs. It is often used to implement object-oriented style program using pure C. However, with virtual methods in C++, the need to use pointers of functions is largely eliminated.

Here is an example of how to use it:

int f(int x)
{
  return x + x;
}

int g(int x)
{
  return x * x;
}

int main(void)
{
  int (*pf)(int); // this is the pointer to function

  pf = f;
  printf("%d\n",(*pf)(5)); // this calls f
  pf = g;
  printf("%d\n",(*pf)(5)); // this calls g
  return 0;
}



Copyright © 2006-09-25 by Tak Auyeung