C - Pointers to Functions


Declaring a Pointer to a Function

Consider the following code:

int (*pfunction) (int);

This declares a variable that is a pointer to a function.

The name of the pointer is pfunction, and it can only point to functions that have one parameter of type int and that return a value of type int.

Consider the following function:

int sum(int a, int b);                 // Calculates a+b

You could store its address in a function pointer that you declare like this:

int (*pfun)(int, int) = sum;

You can now call sum() through the function pointer like this:

int result = pfun(45, 55);

The following code defines three functions that have the same parameter and return types and use a pointer to a function to call each of them in turn.


#include <stdio.h>

// Function prototypes
int sum(int, int);
int product(int, int);
int difference(int, int);

int main(void)
  int a = 10;                         // Initial value for a
  int b = 5;                          // Initial value for b
  int result = 0;                     // Storage for results
  int(*pfun)(int, int);              // Function pointer declaration

  pfun = sum;                         // Points to function sum()
  result = pfun(a, b);                // Call sum() through pointer
  printf("pfun = sum result = %2d\n", result);

  pfun = product;                     // Points to function product()
  result = pfun(a, b);                // Call product() through pointer
  printf("pfun = product result = %2d\n", result);
  pfun = difference;                  // Points to function difference()
  result = pfun(a, b);                // Call difference() through pointer
  printf("pfun = difference result = %2d\n", result);
  return 0;//w w w  .j av  a 2  s  .  c om
int sum(int x, int y)
  return x + y;

int product(int x, int y)
  return x * y;

int difference(int x, int y)
  return x - y;


Related Topics