Function Returning Itself

后端 未结 9 735
鱼传尺愫
鱼传尺愫 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: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
    

提交回复
热议问题