Objects First


Functions as Parameters

C allows a function to be a formal parameter of another function. For example: suppose we want to solve f(x) = 0 by Newton's method. We define a function that takes an initial guess, x, and a function and its derivative as arguments (Newton's method needs the function and its derivative):
double Newton( double x, double (*f)( double ), double (*f1)( double ) ) {
  double r;
  ...
  return r;
  }
The parentheses around *f and *f1 indicate that they are pointers to a function, not a function that returns a pointer to a double!

So we could find a solution to

sin(x) = 0
near x = 0.5 by calling:
      guess = 0.5;
      x = Newton( guess, sin, cos );
Note that we just pass the names of the functions, sin and cos as these are pointers to the functions themselves.

To invoke the functions in the body of Newton, the parameter is simply the name of a function, which is invoked in the usual way:

#include <stdio.h>
#include <math.h>

#include "Newton.h"

static double eps = 1.0e-10;
#define MAX_ITER    1e4

/* Solve f(x) = 0 for a function f which has derivative f1,
   starting from an initial guess x
*/
double Newton( double x, double (*f)( double ), double (*f1)( double ) ) {
  double next;
  int cnt = 0;

  do {
    next = x - f(x)/f1(x);
    if ( fabs(next - x) <= eps ) return x;
    x = next;
    }
  while ( (cnt++) < MAX_ITER );
  fprintf(stderr,"Newton exceeded iteration count!\n");
  return next;
  }

Key terms

Continue on to Other Object-Oriented Languages Back to the Table of Contents
© John Morris, 1998