Can recursion have an endless loop?

569 views Asked by At

I hear people say a lot of times recursion can be an “endless loop”, but wouldn’t that saying be only applied to something done with loops. Would it be valid and correct to say “endless loop” for recursion like that? Wouldn’t it better to say “endless recursion”?

1

There are 1 answers

0
Sylwester On

A tail recursion can be considered a iterative loop. This is the only type of infinite recursion that doesn't swiftly end with a stack overflow error.

If you write this in a compliant ECMAScript 2016 implementation

const test = (n) => test(n + 1);
test(0);

It will hang forever and never cause a stack overflow. The browser will hang as it is a busy loop, but it will never get a stack overflow because tail calls are optimized into something like this:

const test = (n) => {
  while(true) {
    n++;
  }
}
test(0);

If you consider the bottom one an infinite loop, the first one is not different. If this was C both would be turning into very similar assembly code using gotos, because assembly does not have while loops nor functions.