Function pointer
From Wikipedia, the free encyclopedia
A function pointer is a type of pointer in the C, C++ and D programming languages. A function pointer, when dereferenced, calls a function with arguments placed after the dereferenced pointer just like a normal function. Function pointers are of the type the function returns.
In programming languages like C, function pointers are used to eliminate giant switch statements. Java doesn't have function pointers. You could implement function pointers in Java using Command design pattern. [1]
[edit] 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 <stdio.h> int sum = 0; /* store sum */ int product = 1; /* store product */ void fsum(int value) { sum += value; } void fproduct(int value) { product *= value; } void map_function_on_list(list *L, void (*functionptr)(int)) { listnode *node; node = L->first; while (node != NULL) { functionptr(node->value); /* call function pointer */ node = node->next; } } int main() { list *L; ... fill list with values ... map_function_on_list(L, fsum); /* calculate the sum */ map_function_on_list(L, fproduct); /* calculate product */ printf("Sum: %d\nProduct %d\n", sum, product); /* 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.
In languages that support first-class functions, functions are regarded as data and can be passed, returned, and created dynamically directly by other functions; eliminating the need for function pointers.
[edit] External link
- Function Pointer Tutorials — guide to C/C++ function pointers, callbacks, and functors