In C/C++, functions can call themselves. This is called recursion, and a function that calls itself is said to be recursive. A simple example is the function factr( ) shown here, which computes the factorial of an integer. The factorial of a number N is the product of all the whole numbers from 1 to N. For example, 3 factorial is 1 × 2 × 3, or 6.
// Compute the factorial of a number using recursion. int factr(int n) { int answer; if(n==1) return 1; answer = factr(n-1)*n; return answer; }
When factr( ) is called with an argument of 1, the function returns 1; otherwise, it returns the product of factr(n–1) * n. To evaluate this expression, factr( ) is called with n–1. This process continues until n equals 1 and the calls to the function begin returning. When factr( ) finally returns to the original caller, the final return value will be the factorial of the original argument.
When a function calls itself, new local variables and parameters are allocated storage on the stack, and the function code is executed with these new variables from its beginning. A recursive call does not make a new copy of the function. Only the arguments and local variables are new. As each recursive call returns, the old local variables and parameters are removed from the stack and execution resumes at the point of the recursive call inside the function. Recursive functions could be said to “telescope” out and back.