Function Pointer Article Index for
Function
Website Links For
Function
 

Information About

Function Pointer





AN EXAMPLE IN C

Suppose we have a linked list containing integer values. We want to perform two operations on this list: 1) sum up all values, and 2) calculate the product of all values:


#include

  • store sum ---/

  • store product ---/


void fsum(int value)
{ sum += value; }

void fproduct(int value)
  • = value; }


  • L, void (---functionptr)(int))

  • {

  • node;

  • node = L->first;

while (node != NULL)
{
  • call function pointer ---/

  • node = node->next;

}
}

int main()
{
  • L;

  • ... fill list with values ...


  • calculate the sum ---/

  • calculate product ---/


printf("Sum: %d
Product %d
  • display results ---/

  • }




Clearly, function pointers provide a powerful mechanism for programming. Imagine rewriting the above code without function pointers. The fsum() and fproduct() function would both require loops iterating through the linked list. What if we also want to have functions that subtract, divide, find the max/min value, etc? Function pointers are the clear choice of implementing such functions.

Function Objects , or functors, are similar to function pointers, but in some ways they are more flexible. For example, you can use a functor to emulate a Closure .


FUNCTION VALUES

Similar to function pointers, function values provide a mechanism for passing functions as arguments. In certain languages, such as ML, functions can be stored (or mapped to) values. This allows passing expressions as arguments. To demonstrate this, the following example determines if the elements in a list are even or odd:



fun map(F, nil) = nil