[net.lang.c] Function returning a pointer to a function.

rudy@ecr1.UUCP (Rudy Wortel) (07/23/85)

>	Is it legal for a function to return a pointer to a function?
>It seems like it should be, but if so, how would one define and
>declare such a function?

It is quite legal for a function to return a pointer to another function
as long as the type of the returned function is known. Since there are
no generic pointers in C it follows that you cannot return a generic
function pointer.

A declaration for a function returning a pointer to a function returning
an integer would look like:

extern int (*func())();

The rational behind the declaration may be made a little clearer by 
examining the various components of the declaration itself shown 
below. 

int (*func())()
      ^^^^              func is
          ^^            a function returning
     ^                  a pointer to
             ^^         a function returning
^^^                     an integer

An actual function definition might look like

int (*func( arg ))()
char arg;
{
int nfunc(), yfunc();

	if( arg == 'y' || arg == 'Y' ){
		return yfunc;
	}else{
		return nfunc;
	}
}

The return statements return the name of the desired function. The C 
compiler will arrange for the address ( a pointer ) of the function 
much in the same way that an array name produces a pointer to the 
first element of the array. 

To use a pointer to a function in another function the syntax may
sometimes confuse.

int who_cares ( argument )
char argument;
{
int (*yes_no)();
int (*yuk)();

	yes_no = func( argument );

	/* K&R says proper use of a pointer to a function as */

	(*yes_no)( "This is the call though the pointer" );

	/* some compilers do not require the dereferencing which  */
	/* sometimes looks like there is an actual function yes_no */

	yes_no( "This is the call though the pointer" );

	/* if the function yuk also returns a pointer to a function */
	/* then chaining function call together would look like */

	yuk( YUK_ARGUMENT )( "argument to the function yuk returned" );

	/* the function yuk is called with the argument YUK_ARGUMENT the */
	/* the function it returns is then called with the string shown */

	/* personally i don't think i would use this regularly */
	/* and you thought ++i was confusing */
}

------------- end of semi useful stuff ---------------------------

To be totaly unproffessional, unreadable, nonportable and just plain
useless, but never the less correct, the following declaration

char *(*(*(*yuk())())[])();

declares yuk to be a function returning a pointer to a function 
returning a pointer to an array of pointers to functions returning 
pointers to chars.


PS
This should give the net something else to complian about.
All flames will be used to heat my house this winter.