简体   繁体   中英

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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