[net.lang.c] Functions returning pointers to functions

john@genrad.UUCP (John Nelson) (12/13/83)

I believe that the easiest way to get around the problem is to use
a typedef:

typedef int (*FUNCTION)();

then you can declare the function returning a pointer to function as:

FUNCTION getroutine(name, table)

This SHOULD work with all K&R C compilers

garys@bunkerb.UUCP (Gary Samuelson) (12/14/83)

In reply to Steve Summit, who wanted a function returning a
pointer to a function returning an integer:

I tried to write this reply in the same style as your request,
but I guess I don't speak King James English well enough.  Will
Today's English suffice :-) ?

Using a typedef divides the declaration into bite-sized pieces,
which the compiler can swallow.

The following program, which I have compiled and run on our VAX
(4.1BSD), contains such a function.  Simply tear along the dotted
line.

Gary Samuelson
decvax!ittvax!bunker!bunkerb!garys
-------------------------------------------------
/*
 * a couple of functions which return integers
 */

int g( x )
int x;
{
	return( x + x );
}

int h( x )
int x;
{
	return( x * x );
}

/*
 * A function which returns a pointer to a function
 * which returns an integer.
 */

typedef int (*ifp)() ;
ifp f( a )
int a;
{
if( a == 0 )
	return( g );
else
	return( h );
}

main()
{
	printf( "%d\n", ((*f)( 0 )) ( 4 ) );
	printf( "%d\n", ((*f)( 1 )) ( 4 ) );
}

kissell@flairvax.UUCP (Kevin Kissell) (12/15/83)

To declare a function returning a pointer to a function returning an
integer, the construct

int (*funcfunc())()

is pretty standard.  Things get confusing when the parameters are added.
Steve's example of the form

	int (*getroutine())(name, table)

does indeed fail under 4.1, but

	int (*getroutine(name, table))()

will work just fine, and is more correct if you think about it.
What I can't figure is how the first version worked under 2.8!

		Kevin D. Kissell
		Fairchild Research Center
		Advanced Processor Development
		uucp:{ucbvax!sun decvax allegra}!decwrl!flairvax!kissell

george@mnetor.UUCP (George Hart) (07/18/85)

I'm sorry I've lost the original reference but someone asked
how to declare a function returning a pointer to a function
(returning whatever).

Here's some trivial code that illustrates one way.  Using typedef's is better
way especially if you are going to use multiple levels of indirection
(maybe not a good idea to begin with).

extern int printf();

main()
{
    int (*func())();

    (func())("This is the %dst string.\n",1);
}

int (*func())()
{
    return(printf);
}

-- 


Regards,

George Hart, Computer X Canada Ltd.
UUCP: {allegra|decvax|linus|ihnp4}!utzoo!mnetor!george
BELL: (416)475-8980