petrushkagoogol
- 28
- 4
Upto how many levels of recursion can be used in an algorithm to avoid stack overflow error ?
petrushkagoogol said:Upto how many levels of recursion can be used in an algorithm to avoid stack overflow error ?
I don't think so. In recursion of any kind, the return address and any parameters have to be pushed onto the stack, something that is not done when a loop executes. Eventually the program will run out of available stack storage.Irene Kaminkowa said:It depends.
For example, tail recursion is as good as any iteration.
If the recursive function takes parameters, I don't see how a compiler could rewrite a function call as a jump. The compiler would still have to push the parameters onto the stack.Irene Kaminkowa said:It depends.
A compiler (interpreter) may treat tail-recursive calls as jumps not function calls. Then, the space is constant.
Exactly. Many compilers are very good at recognizing tail recursion. It's called "Tail call optimization". Some interpreters are also good at recognizing tail recursion (e.g., many dialects of Lisp), many others are not (python (Guido hates TCO), perl, ruby, ...).Irene Kaminkowa said:It depends.
A compiler (interpreter) may treat tail-recursive calls as jumps not function calls. Then, the space is constant.
Tail recursion is a very special kind of recursion. The following C function to compute n! is recursive but it is not tail recursive:Mark44 said:If the recursive function takes parameters, I don't see how a compiler could rewrite a function call as a jump. The compiler would still have to push the parameters onto the stack.
unsigned factorial (unsigned n) {
if (n <= 1) {
return 1;
} else {
return n * factorial(n-1);
}
unsigned factorial_helper (unsigned n, unsigned prod) {
if (n <= 1) {
return prod;
} else {
return factorial_helper(n-1, n*prod);
}
}
unsigned factorial (unsigned n) {
return factorial_helper(n, 1);
}
Consider GCD - it can be implemented as tail recursion.Mark44 said:The compiler would still have to push the parameters onto the stack
I just showed one for factorial. It can be implemented as tail recursion.Irene Kaminkowa said:Consider GCD - it can be implemented as tail recursion.
Factorial - cannot.