Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function Returning Itself

Tags:

c

function

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?

like image 393
Drew McGowen Avatar asked Jul 08 '13 21:07

Drew McGowen


People also ask

Can a function return itself?

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.

What is the function returning?

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.

Does returning end a function?

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.

Can a function return a function pointer?

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.


2 Answers

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.

like image 120
ouah Avatar answered Oct 02 '22 17:10

ouah


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.

like image 45
Drew McGowen Avatar answered Oct 02 '22 15:10

Drew McGowen