Using recursion

In most cases the memory overhead of a call stack is unimportant. However, when you use recursion it is possible to build up a long chain of stack frames. As the name suggests, recursion is when a function calls itself. A simple example is a function that calculates a factorial:

    int factorial(int n)     {         if (n > 1) return n ∗ factorial(n − 1);         return 1;     }

If you call this for 4, the following calls are made:

    factorial(4) returns 4 * factorial(3)         factorial(3) returns 3 * factorial(2)             factorial(2) returns 2 * factorial(1)                 factorial(1) returns 1

The important point is that in the recursive function there must be at least one way to leave the function without recursion. In this case, it will be when factorial is called ...

Get Beginning C++ Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.