C - Pointers to Functions As Arguments

Introduction

You can use a pointer to a function as an argument to a function.

You can call different function depending on which function is passed as the argument.

Demo

#include <stdio.h>

// Function prototypes
int sum(int, int);
int product(int, int);
int difference(int, int);
int any_function(int(*pfun)(int, int), int x, int y);

int main(void)
{
  int a = 10;                         // Initial value for a
  int b = 5;                          // Initial value for b
  int result = 0;                     // Storage for results
  int(*pf)(int, int) = sum;          // Pointer to function

                     // Passing a pointer to a function
  result = any_function(pf, a, b);//from   w  w w. java2s .co  m

  printf("result = %2d\n", result);

  // Passing the address of a function
  result = any_function(product, a, b);

  printf("result = %2d\n", result);

  printf("result = %2d\n", any_function(difference, a, b));
  return 0;
}

// Definition of a function to call a function
int any_function(int(*pfun)(int, int), int x, int y)
{
  return pfun(x, y);
}

// Definition of the function sum
int sum(int x, int y)
{
  return x + y;
}
// Definition of the function product
int product(int x, int y)
{
  return x * y;
}

// Definition of the function difference
int difference(int x, int y)
{
  return x - y;
}

Result

The function that will accept a pointer to a function as an argument is any_function().

The prototype for this function is the following:

int any_function(int(*pfun)(int, int), int x, int y);

The any_function() function has three parameters.

The first parameter type is a pointer to a function that accepts two integer arguments and returns an integer.

The last two parameters are integers that will be used in the call of the function specified by the first parameter.

Related Topic