简体   繁体   English

如何启用递归函数以避免堆栈溢出?

[英]How to enable a recursive function to avoid stack overflow?

If I have a recursive function in Java, I can call it infinitely with the following code: 如果我在Java中具有递归函数,则可以使用以下代码无限调用它:

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

How can I do this in C++? 如何在C ++中做到这一点?

There is no standard way to force a c++ compiler to perform tail-call optimisation on a recursive function. 没有强制C ++编译器对递归函数执行尾调用优化的标准方法。

Having said that, gcc8 with -O2 will actually perform tail-call optimisation when possible. 话虽如此,带有-O2的gcc8实际上会在可能的情况下执行尾部调用优化。

https://godbolt.org/z/tSDODA https://godbolt.org/z/tSDODA

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM