hawley (11/11/82)
A long time ago, I sent out a note about C function pointers to some other newsgroup. I am the only person I know who likes and uses these things. Here is an idiom I commonly run into: /* This file gives a simple example of C function pointers. * Function pointers are a VERY useful construct. * A typical application: keep a table of functions, * choose a function in the table, and call it. * * Function pointer declarations can be confusing. * Here is how I "read" these declarations: * * int f; /* "f is an int." * * int *f; /* "f is a pointer to an int" * * int (*f)(); /* "f is a pointer to a function returning an int" * * * The '*' means "is a pointer to a" and the empty parens '()' mean * "function returning". The type "pointer to function returning" * is written "(*)()", and can be used in casts, sizeofs(), etc. * * For more information: send me mail. * */ int a(), b(), c(), d(), e(); /* Some dull functions. */ int (*ftable[])() = /* A table of functions: */ { /* ie, "ftable is an array of pointers */ a, b, c, d, e /* to functions that return an int." */ }; /* N_FUNCTIONS is the number of functions in the function table. */ # define N_FUNCTIONS ( sizeof( ftable )/sizeof( ftable[0] ) ) /* This could also have been more opaquely and dangerously written as: # define N_FUNCTIONS ( sizeof( ftable )/sizeof( int (*)() ) ) */ main() { extern int (*ftable[])(); /* the function table */ int (*function)(); /* a function pointer, taken from ftable */ int i; /* Loop through the functions in the table, */ /* calling each one: */ for (i = 0; i < N_FUNCTIONS; i++) { function = ftable[i]; (*function)("Frootle."); /* call function i */ } } /* Here are the functions "a" through "e". They are all the same, all dull. */ a(s) char *s; { printf("I am function A. My argument is \"%s\"\n", s); } b(s) char *s; { printf("I am function B. My argument is \"%s\"\n", s); } c(s) char *s; { printf("I am function C. My argument is \"%s\"\n", s); } d(s) char *s; { printf("I am function D. My argument is \"%s\"\n", s); } e(s) char *s; { printf("I am function E. My argument is \"%s\"\n", s); }