Function Returning Itself

后端 未结 9 668
鱼传尺愫
鱼传尺愫 2020-11-27 04:59

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 retur

相关标签:
9条回答
  • 2020-11-27 05:30

    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.

    0 讨论(0)
  • 2020-11-27 05:31

    You can't cast function pointers to void* (they can be different sizes), but that's not a problem since we can cast to another function pointer type and cast it back to get the original value.

    typedef void (*fun2)();
    typedef fun2 (*fun1)();
    
    fun2 rec_fun()
    {
        puts("Called a function");
        return (fun2)rec_fun;
    }
    
    // later in code...
    fun1 fp = (fun1)((fun1)rec_fun())();
    fp();
    

    Output:

    Called a function
    Called a function
    Called a function
    
    0 讨论(0)
  • 2020-11-27 05:32

    In other words, is it possible for a function to return itself?

    It depends on what you mean by "itself"; if you mean a pointer to itself then the answer is yes! While it is not possible for a function to return its type a function can return a pointer to itself and this pointer can then be converted to the appropriate type before calling.

    The details are explained in the question comp.lang.c faq: Function that can return a pointer to a function of the same type.

    Check my answer for details.

    0 讨论(0)
提交回复
热议问题