user3711004
user3711004

Reputation: 65

How do I declare a function that returns a pointer to a function that returns a function pointer without using a typedef in C?

I was wondering how I write a function which returns a pointer to a function which returns a function pointer, without a typedef. For instance a function which returns a function pointer can be define as:

type (*f_name(..))(..){..}

So this returns a pointer to a function that returns a 'type', now how do you declare the function if the 'type' is a function pointer. But as my supervisor does not want typedefs used I can't use them.

Thanks for any help you can give.

Upvotes: 6

Views: 1828

Answers (2)

2501
2501

Reputation: 25752

First we write a function taking an int and returning a float.

float First( int f )
{
    return ( float )f ;
}

Then we write a function taking nothing and returning a pointer to a function taking an int and returning a float.
This pointer is the same type as First.

float ( *Second( void ) )( int ) 
{
    float (*f)( int ) = First ;

return f ;
}

Finally we write a function taking a char and returning a pointer to a function taking nothing and returning a pointer to a function taking an int and returning a float. This pointer is the same type as Second.

float ( *( *Third( char c ) )( void ) )( int )
{
    ( void )c ;
    float ( *(*s)( void ) )( int ) = Second ;

return s ;
}

If you place the prototypes along one another, the weird syntax starts to make sense:

float       First                    ( int ) ;
float (    *Second         ( void ) )( int ) ;
float ( *( *Third( char ) )( void ) )( int ) ;

The only difference to returning an non-function pointer is that function pointers parameters go at the end of the declaration, and the brackets:

         type*  Name( void ) ; 
function_type (*Name( void ) )( int ) ;

Upvotes: 3

drRobertz
drRobertz

Reputation: 3638

For questions like this there is a nifty utility called cdecl (http://cdecl.org/) which translates between english and C declarations.

For instance

cdecl> declare f as function (int) returning pointer to function (char) returning pointer to function (void) returning long

gives the answer

long (*(*f(int ))(char ))(void )

and, in the other direction,

cdecl> explain int (*(*g(float))(double, double))(char)

gives

declare g as function (float) returning pointer to function (double, double) returning pointer to function (char) returning int

Upvotes: 7

Related Questions