[英]Is this not tail recursive? (stack overflow error)
This is a small function I have written to check whether an integer is a prime or not: 这是我编写的一个小函数,用于检查整数是否为质数:
int prime(int x, int y = 2)
{
if(y <= x/2)
{
if((x % y) == 0)
return 0;
}
else
return 1;
return prime(x, ++y);
}
Now, I compile it with visual studio 2012, and if i give it a large value such as 105943, a stack overflow error occurs and the code breaks. 现在,我使用Visual Studio 2012对其进行编译,如果我给它一个较大的值(如105943),则会发生堆栈溢出错误,并且代码会中断。 Now, is this function not tail recursive? 现在,此函数不是尾递归吗? If so then a stack shouldn't be maintained for the recursive calls, and an overflow should not occur? 如果是这样,则不应为递归调用维护堆栈,并且不应发生溢出?
What am I not getting here exactly? 我到底要来什么?
It is a tail recursive function, but there's no requirement for any compiler to optimise tail recursion into a loop. 它是一个尾递归函数,但不需要任何编译器将尾递归优化为循环。 The chances are if you've got optimisation levels set high enough, it'll do so. 如果您将优化级别设置得足够高,则很有可能会这样做。 But that's all. 但是,仅此而已。
LISP (and derived languages) are the only ones I know of where tail recursion is actually a requirement of the implementation. LISP(和派生语言)是我所知道的仅有尾递归实际上是实现要求的地方。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.