                        POINTERS TO C FUNCTIONS

                            Matthew Probert
                           Servile  Software


The C programming language allows a pointer to point to the address of 
a function, and this pointer to be called rather than specifying the 
function. This is used by interrupt changing functions and may be used 
for indexing functions rather than using switch statements. For 
example; 

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

/* Declare an array of pointers to functions 'fp[]' */
double (*fp[7])(double x); 

void main()
{ 
    double x; 
    int p; 

    /* Initialise each pointer to function array element */
    fp[0] = sin; 
    fp[1] = cos; 
    fp[2] = acos; 
    fp[3] = asin; 
    fp[4] = tan; 
    fp[5] = atan; 
    fp[6] = ceil; 

    p = 4; 

    /* Call the tan() function via the pointer to the function, 
       fp[4] */

    x = fp[p](1.5); 
    printf("\nResult %lf",x); 
} 

This example program defines an array of pointers to functions, 
(*fp[])() that are then called dependant upon the value in the 
indexing variable p. This program could also be written; 


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

void main()
{ 
    double x; 
    int p; 

    p = 4; 

    switch(p)
    { 
        case 0 : x = sin(1.5); 
                 break; 
        case 1 : x = cos(1.5); 
                 break; 
        case 2 : x = acos(1.5); 
                 break; 
        case 3 : x = asin(1.5); 
                 break; 
        case 4 : x = tan(1.5); 
                 break; 
        case 5 : x = atan(1.5); 
                 break; 
        case 6 : x = ceil(1.5); 
                 break; 
    } 
    puts("\nResult %lf",x); 
} 

The first example, using pointers to the functions, compiles into much 
smaller code and executes faster than the second example. 

The table of pointers to functions is a useful facility when writing 
language interpreters, the program compares an entered instruction 
against a table of key words that results in an index variable being 
set and then the program simply needs to call the function pointer 
indexed by the variable, rather than wading through a lengthy switch() 
statement. 

