6.28 String Functions6 Notes6.26 Recursion6.27 Function pointers

6.27 Function pointers

It is some times desirable to be able to pass the address of a function to another part of a program. This can be useful in sorts. It can also be required for certain calls to the operating system for error handling and signals.

The example is about as simple as it get. There are two different functions, one twice, doubles a number, and half, divides a number by two. They are called alternately. The address of the function called is also printed.

The program:


/* Program to look at function pointers       */ 
/* L Taber   April 8, 2001   PCC              */

#include <stdio.h> 

int twice(int x)
  { return x*2; }  /* double number           */
int half(int x)
  { return x/2; }  /* divide number by 2      */

int main() 
{
int i;
int (*function)(int);

for( i=0; i<10; i++)
  {           /* If i is odd, function = twice    */
  if( i&1 ) function = &twice; 
  else      function = &half;
              /* call function and print results  */
              /* Print address of function in [ ] */
  printf(" f[%p](%i) = %d %c",
            function, i,  function(i), i&1 ? '\n' : ' ' );

  }
}

The source is available at:
ftp://lt.tucson.az.us/pub/c/function-ptr.c

And the output:

 f[0x80483f4](0) = 0   f[0x80483e0](1) = 2 
 f[0x80483f4](2) = 1   f[0x80483e0](3) = 6 
 f[0x80483f4](4) = 2   f[0x80483e0](5) = 10 
 f[0x80483f4](6) = 3   f[0x80483e0](7) = 14 
 f[0x80483f4](8) = 4   f[0x80483e0](9) = 18 

Instructor: Louis Taber, louis.taber.at.pima at gmail dot com (520) 206-6850
My web site in Cleveland, OH
The Pima Community College web site

6.28 String Functions6 Notes6.26 Recursion6.27 Function pointers