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.
We would need to declare typedef for it and typedef will do the job or then return void*.
Return Function Pointer From Function: To return a function pointer from a function, the return type of function should be a pointer to another function. But the compiler doesn't accept such a return type for a function, so we need to define a type that represents that particular function pointer.
Pointers in C programming language is a variable which is used to store the memory address of another variable. We can pass pointers to the function as well as return pointer from a function.
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
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 ) ;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With