1

If I have a recursive function in Java, I can call it infinitely with the following code:

void recfunction()
{
    recfunction();
    System.gc();
}

How can I do this in C++?

12
  • 2
    You can do this in Java? Well, in C++, the above code, technically, is 'infinite', but, in practice will quickly exhaust your stack and crash. Not sure what the point of it is. Commented Apr 17, 2019 at 19:14
  • 2
    Get rid of the recursion. Commented Apr 17, 2019 at 19:17
  • 8
    I don't think you can do that in java Commented Apr 17, 2019 at 19:20
  • 3
    I'm not aware of any language using a garbage collector that would clean the stack - garbage collectors usually only manage heap allocated memory Commented Apr 17, 2019 at 19:24
  • 3
    Several misconceptions here: 1: The above breaks Java (unless the compiler optimizes out the tail recursion). Same thing happens in C++. 2: Garbage collection does not affect the stack (it cleans the heap). 3: C++ does have garbage collectors (they are just not very popular as we have a better method of cleaning up memory that is deterministic). Commented Apr 17, 2019 at 19:47

1 Answer 1

2

There is no standard way to force a c++ compiler to perform tail-call optimisation on a recursive function.

Having said that, gcc8 with -O2 will actually perform tail-call optimisation when possible.

https://godbolt.org/z/tSDODA

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.