Function Pointers

In C++, any function name without parenthesis is considered a pointer to the function. In other words, the function name is the location of the body of the function in memory.

Function pointers allow for writing functions that can take another function as an argument. To specify a function as an argument to another function, specify

void function1( void (*f) (int) );

void function2( void (*f) (double &) );

function1 is a function that takes as its argument is any void function that takes an integer as its argument. function2 is a function that takes as its argument any void function that takes a reference to a double as its argument.

In both examples, f is the address of the function, *f dereferences the address, (*f)(argument) is a call to the function

For example:

double sum( double (*f)(int), int lower, int upper )
  {
  double result = 0;
  
  for( int i = lower; i <= upper; i++)
    result += (*f)(i);
    
  return result;
  }


double f1( int x )
  {
  return x * 7;
  }


double f2( int y )
  {
  return (double) y / 5;
  }
  

cout << sum( f1, 1, 5 );

cout << sum( f2, 2, 4 );