Possible Duplicate:
What is the point of function pointers?
How pointer function work, and where is the difference ( not abstract like encapsulatin ) from methods
Possible Duplicate:
What is the point of function pointers?
How pointer function work, and where is the difference ( not abstract like encapsulatin ) from methods
Function pointer store entry address of a function. The type of pointer specify how this function should be called: return type, arguments and calling convention. When you call function pointer compiler generates instructions to call function at given address.
Methods are closer to functions. Method is referenced by name and replaced by actual address by compiler (if non virtual method) or via Virtual Method Table (if method is virtual). It is possible to have pointer to method that will be much like the function pointer.
in C# we call them delegates (but delegates are more then just pointers)... basically it's a pointer (a variable that is a memory location as opposed to an int, char, etc.) to a function (or method, etc), that you can then invoke. The main use is to provide a means of calling a method in your code that you don't know at compile time.
link'o'rama:
Wikipedia
A Tutorial
Everything has a type in c/c++/etc. Even "main". What type is it? It's (approximately - main is a weird example) a:
int(*)(int,char**)
So all functions have types. You can make a variable that stores pointers to those functions, then use them like functions themselves:
# cat f.c
#include <stdio.h>
typedef int (*func_that_returns_int_and_takes_int_t)(int);
int foo( int i ) { fprintf( stdout, "foo: %d\n", i ); }
int bar( int i ) { fprintf( stdout, "bar: %d\n", i ); }
int main( int argc, char **argv )
{
func_that_returns_int_and_takes_int_t f[4] = { foo, bar, bar, foo };
int i;
for( i=0; i<4; i++ ) { f[i](i); }
}
# gcc f.c -o f
# ./f
foo: 0
bar: 1
bar: 2
foo: 3
Function pointers can be used to modularize the interface for a function call (a concept similar to a functor), so that a function not known at compile time can be used. It also allows iterating through an array of functions, as above, which would otherwise not be possible without hardcoding them.
In higher-level languages, like perl/python/java/emcascripts, these are used all over for "passing functions" to add-event-handler functions, as well as map/reduce/sort. You never really pass "whole functions" around, you pass pointers to them.