Is it possible to declare some function type func_t
which returns that type, func_t
?
In other words, is it possible for a function to return itself?
// func_t is declared as some sort of function pointer func_t foo(void *arg) { return &foo; }
Or would I have to use void *
and typecasting?
Am I missing something? @SamuelEbert, yes this function returns itself, but also is bloated with functional which is useless for the context of the question and focuses on that additional functional.
A return is a value that a function returns to the calling script or function when it completes its task. A return value can be any one of the four variable types: handle, integer, object, or string. The type of value your function returns depends largely on the task it performs.
A return statement ends the execution of a function, and returns control to the calling function. Execution resumes in the calling function at the point immediately following the call. A return statement can return a value to the calling 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.
No, you cannot declare recursive function types in C. Except inside a structure (or an union), it's not possible to declare a recursive type in C.
Now for the void *
solution, void *
is only guaranteed to hold pointers to objects and not pointers to functions. Being able to convert function pointers and void *
is available only as an extension.
A possible solution with structs:
struct func_wrap { struct func_wrap (*func)(void); }; struct func_wrap func_test(void) { struct func_wrap self; self.func = func_test; return self; }
Compiling with gcc -Wall
gave no warnings, but I'm not sure if this is 100% portable.
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