Perverse pointers...
utzoo!decvax!ucbvax!unix-wizards
utzoo!decvax!ucbvax!unix-wizards
Sun Dec 13 22:53:22 AEST 1981
>From decvax!yale-comix!hawley at 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.
*/
More information about the Comp.unix.wizards
mailing list