next up previous contents index
Next: Void pointers Up: Pointers Previous: Subroutine return types   Contents   Index


Function pointers

Another place that pointers find a valuable use is as a pointer to a function. Consider the following example.
void young(int);
void old(int);

int main(void) {
  void (*fp)(int);
  int age;
  printf("How old are you? ");
  scanf("%d", &age);
  fp = (age > 30) ? old : young;
  fp(age);
  return 0;
}
void young(int n) {
  printf("Being only %d, you sure are young.\n", n);
}
void old(int m) {
  printf("Being already %d, you sure are old.\n", m);
}
The function pointer *fp is declared here as void (*fp)(int), which specifies both the return type (void) and the types of arguments (int) of the function. We then assign the pointer to a particular function, and having done so, can then call the function just as we normally would.

Function pointers are often used within subroutines in cases where one would want the subroutine to be able to work with classes of functions whose names one might not know until the program is running. Consider the following variation of the above program:

void young(int);
void old(int);
void greeting(void (*)(int), int);
int main(void) {
  int age;
  printf("How old are you? ");
  scanf("%d", &age);
  if (age > 30) {
    greeting(old, age);
  }
  else {
    greeting(young, age);
  }
  return 0;
}
void greeting(void (*fp)(int), int k) {
  fp(k);
}
void young(int n) {
  printf("Being only %d, you sure are young.\n", n);
}
void old(int m) {
  printf("Being already %d, you sure are old.\n", m);
}
Here, the greeting routine can accept any function of type void and single argument int.