Text File

Aucbvax.5468 fa.unix-wizards utzoo!decvax!ucbvax!unix-wizards Sun Dec 13 22:53:22 1981 Perverse pointers... >From decvax!yale-comix!hawley@Berkeley Sun Dec 13 22:52:12 1981 /* Chapter II from my new book -- * * "The last word on pointers to functions in C" * * by mike hawley (decvax!yale-comix!hawley) * * Pointers to functions in C can be really useful; * unfortunately, more people don't use them. * Some of you C hackers may get a charge out of this... */

main() { int f(); /* f() returns my favorite integer. */ int (*fp)(); /* fp holds a pointer to a function like f */ int (*ret_f())(); /* ret_f() passes the pointer to "f()". */ long ret_f2(); /* Works like ret_f(), but must be coerced. */ int (* (*ret_ret_f())())(); /* Horrors! */

printf(" My favorite integer is: %d\n", f());

fp = f; /* The usual way to pass function pointers: */ printf(" My favorite integer is: %d\n", (*fp)());

fp = ret_f(); /* Another way to pass function pointers: */ printf(" My favorite integer is: %d\n", (*fp)());

fp = (int(*)()) ret_f2(); /* Yet another way, using casts. */ printf(" My favorite integer is: %d\n", (*fp)());

fp = (*ret_ret_f())(); /* . .... Oh, come ON!! */ printf(" My favorite integer is: %d\n", (*fp)()); }

f() /* f() returns my favorite integer. */ { return (147); }

int (*ret_f())() /* ret_f() returns f, a pointer to a function returning int. */ { int f(); return (f); }

long ret_f2() /* Does what ret_f() does, but requires the use of casts. */ { int f(); return ((long)f); }

/* The following function returns a pointer to "ret_f", a function that * returns a pointer to a function that returns an int. * HA! You know, the compiler even believes this! * These critters are very shy; consequently, you don't see them * around too often! */ int (* (*ret_ret_f())() )() { int (*ret_f())(); return (ret_f); }

/* Why? A function like ret_f() can be used, for example, to select * a command from a table of commands, and send back the pointer * to the appropriate function for executing the chosen command. */

----------------------------------------------------------------- gopher://quux.org/ conversion by John Goerzen <jgoerzen@complete.org> of http://communication.ucsd.edu/A-News/

This Usenet Oldnews Archive article may be copied and distributed freely, provided:

1. There is no money collected for the text(s) of the articles.

2. The following notice remains appended to each copy:

The Usenet Oldnews Archive: Compilation Copyright (C) 1981, 1996 Bruce Jones, Henry Spencer, David Wiseman.