Function pointers are generally more useful in C than they are in C++. C++'s object-oriented facilities tend to provide better ways of solving the same kinds of problems that are solved using function pointers in C.
In C, there are many uses for them, so it's hard to answer your question in a few sentences. So, I'll try in a few more sentences
Consider the standard function atexit() which is used to register functions to be called at program termination:
int atexit (void (* function)(void));
It accepts a pointer to a function that accepts no parameters and returns void. To use it, you would define one or more functions of the same type somewhere:
void cleanup1(void)
{
puts("cleanup1"

;
}
void cleanup2(void)
{
puts("cleanup2"

;
}
And then call atexit() like this:
atexit(cleanup1);
atexit(cleanup2);
Another example. Suppose you are writing a C program to process an HTML document. The program scans the document for tags and for each tag it finds, it invokes a different function depending on the tag. To locate the appropriate tag, you could create a lookup table composed of the tag name and function pointer (note that the table is arranged in ascending order by tag name):
typedef void (*tag_f)(char **,int,const char *);
struct tag {
char *tag_name;
tag_f tag_func;
} tag_funcs[]={
{"A",anchor_func},
{"BODY",body_func},
{"BR",br_func}
};
As the lexer code that scans the html document encounters each tag, it does a binary search in the lookup table for a match. It if finds a match, it then calls the appropriate function. with the tag attributes and, for some tags, any text that appears in between the opening and closing tags.
Here's a simple definition for anchor_func() that prints out the tag's attributes and url text:
void anchor_func(char **attribs,int attrib_count,const char *url)
{
int i;
printf("url=%s\n",url);
for (i=0;i<attrib_count;++i) {
printf("attribute %d=%s\n",
i+1,attribs
);
}
}
Obviously, each function can do something vastly different. But the code inside the lexer is simplified somewhat because a single function pointer can be used to call each function.
There are lots and lots more ways to use function pointers. These will undoubtedly become apparent to you as you continue to program in C.
Russ
bobbitts@hotmail.com