Home > Article > Backend Development > What are the exit conditions for a recursive function in C++?
C The exit conditions of recursive functions include: Baseline conditions: Check whether the function reaches a state that can directly return results, usually judging whether a certain condition or parameter value meets the threshold. Recursion termination condition: Alternative to or in addition to the baseline condition, ensuring that the function stops after a certain number of recursive calls, by tracking the recursion depth or setting a maximum recursion depth limit.
C Exit conditions for recursive functions
Recursive functions solve problems by calling themselves repeatedly. To prevent getting stuck in an infinite recursive loop, clear exit conditions must be defined. In C, exit conditions are usually implemented in the following ways:
1. Baseline condition:
bool isEven(int n) { if (n == 0) { // 基线条件:当 n 为 0 时,返回 true return true; } else { return isEven(n - 1); // 递归调用 } }
2. Recursive termination condition:
int fibonacci(int n) { if (n <= 1) { // 基线条件:当 n <= 1 时,返回 n return n; } else if (n > MAX_RECURSION_DEPTH) { // 递归终止条件:当递归深度超过限制时,返回错误值 return -1; } else { return fibonacci(n - 1) + fibonacci(n - 2); // 递归调用 } }
Practical case
The following example function calculates the factorial of a given number:
int factorial(int n) { if (n == 0) { // 基线条件:当 n 为 0 时,返回 1 return 1; } else { return n * factorial(n - 1); // 递归调用 } }
The above is the detailed content of What are the exit conditions for a recursive function in C++?. For more information, please follow other related articles on the PHP Chinese website!