Reading a question in stackoverflow, I wondered whether it's possible to declare a function that takes a pointer to itself. I.e. to make such declaration of foo
, for which the following would be correct:
foo(foo);
The simpliest idea is casting to another function pointer (can't cast to void*
, since it may be smaller), so the function declaration looks like this:
void foo(void (*)());
While that's OK in C (and will work with casting in C++), I wonder, whether it can be done without such hard "reinterpret" casting or losing type information.
In other words, I want the following declaration:
void foo( void (*)( void (*)( void (*) ( ... ))));
but, of course, unlimited declarations are impossible. Naive typedef
ing doesn't help either.
C++ templates are welcome, even if they make the calling code (foo(foo)
) look a bit less succinct, but still finite.
C-style answers that show, how one can drop type information without casting, or other tricks of that sort are, of course, interesting, but won't be accepted.
Pass-by-pointer means to pass a pointer argument in the calling function to the corresponding formal parameter of the called function. The called function can modify the value of the variable to which the pointer argument points. When you use pass-by-pointer, a copy of the pointer is passed to the function.
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.
Function pointers in C need to be declared with an asterisk symbol and function parameters (same as function they will point to) before using them in the program. Declaration of function pointers in C includes return type and data type of different function arguments.
We cannot pass the function as an argument to another function. But we can pass the reference of a function as a parameter by using a function pointer. This process is known as call by reference as the function parameter is passed as a pointer that holds the address of arguments.
Apparently not - see this thread. The type required here would always be infinite.
Another dirty trick.
void Foo( ... )
{
}
int main()
{
Foo( Foo );
}
Above program will compile without any error. But it is not recursive. Following modified function is recursive version with a limiter.
#define RECURSIVE_DEPTH (5)
typedef void ( *FooType )( int, ... );
void Foo( int Depth, ... )
{
void ( *This )( int, ... );
va_list Arguments;
va_start( Arguments, Depth );
if( Depth )
{
This = va_arg( Arguments, FooType );
This( Depth - 1, This );
}
va_end ( Arguments );
}
int main()
{
Foo( RECURSIVE_DEPTH, Foo );
}
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