- Modern C++:Efficient and Scalable Application Development
- Richard Grimes Marius Bancila
- 154字
- 2021-06-10 18:28:06
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 with a parameter of 1. In practice, a function like this should be marked as inline to avoid creating any stack frames at all.