Is there a way for a function to return itself in D?

Lars Kyllingstad public at kyllingen.NOSPAMnet
Tue Oct 14 04:12:55 PDT 2008

Simen Kjaeraas wrote:
> Like the subject says, I wonder if it's possible for a function to 
> return itself.
> No matter how I think of this, I end up with an endless recursive function
> declaration. Creating a functor that does this is simple, so why not a 
> function?

Something like this?


   void* returnSelf()
       Stdout("Hello world!").newline;
       return cast(void*) &returnSelf;

Then the function can be called like this:

   void main()
       void* function() rs;

       // This prints "Hello world!"
       rs = cast(void* function()) returnSelf();

       // This prints "Hello world!" too.

But it's kinda ugly, what with the casts and all. I don't see that it is 
useful either. It makes sense to return a functor, because it is an 
object and has state. A function is stateless, so any "reference" to the 
function will be identical.


More information about the Digitalmars-d-learn mailing list