Answers to questions on recursion

  1. Why is the following recursive function unsafe?
    int recurse(int v)
    {
       return recurse(v);
    }
    
    It has no terminating condition, i.e. there is no alternative to it making a further recursive call. Thus this program will not terminate until it overflows the area of memory allocated for the function calling stack.
  2. Is the following version any safer?
    int recurse(int v)
    {
       if (v>6) return recurse(v);
       return v;
    }
    
    It now has a terminating condition, i.e. there is an alternative to it making a further recursive call. However, there is no means of resetting the values used in assessing the condition, v in fact. Thus this program will either never begin to recurse, since v will start out as 6 or less, or it again will not terminate until it overflows the area of memory allocated for the function calling stack.

Back to the questions.


Back to notes on recursion.