MHB Just a question about recursive functions, no code.

  • Thread starter Thread starter carl123
  • Start date Start date
  • Tags Tags
    Code Functions
Click For Summary
Efficiency in recursive functions in C++ can be enhanced by preventing unnecessary calls. Tail call optimization is a key feature in some C++ compilers that allows the last recursive call in a function to execute without additional stack memory allocation, effectively transforming recursion into a loop and preventing stack overflow. Additionally, techniques like memoization and dynamic programming can be employed to store previously computed values, which is particularly useful in cases like calculating Fibonacci numbers, where repeated computations can be avoided. These strategies collectively improve the performance and reliability of recursive functions in C++.
carl123
Messages
55
Reaction score
0
What are different ways of ensuring efficiency in a recursive function in C++? i.e. Prevent calling your recursive function when not necessary.
 
Last edited:
Technology news on Phys.org
carl123 said:
Prevent calling your recursive function when not necessary.
Ha-ha. If you do any computation that is unnecessary, then you are a... strange programmer.

Some C++ compilers do tail call optimization. Then if the recursive call is the last thing a recursive function does, no memory is allocated on the stack, unlike in a normal function call, and the recursion behaves as a loop. This is important because otherwise a recursive function can easily run out of stack space.

Sometimes it makes sense to store values already computed by a recursive function to avoid re-computing them. Fibonacci numbers is one example. Memoization and dynamic programming are two techniques that store intermediate results.
 
Learn If you want to write code for Python Machine learning, AI Statistics/data analysis Scientific research Web application servers Some microcontrollers JavaScript/Node JS/TypeScript Web sites Web application servers C# Games (Unity) Consumer applications (Windows) Business applications C++ Games (Unreal Engine) Operating systems, device drivers Microcontrollers/embedded systems Consumer applications (Linux) Some more tips: Do not learn C++ (or any other dialect of C) as a...

Similar threads

  • · Replies 16 ·
Replies
16
Views
2K
  • · Replies 11 ·
Replies
11
Views
1K
  • · Replies 17 ·
Replies
17
Views
3K
  • · Replies 12 ·
Replies
12
Views
3K
  • · Replies 5 ·
Replies
5
Views
12K
  • · Replies 39 ·
2
Replies
39
Views
3K
  • · Replies 2 ·
Replies
2
Views
1K
  • · Replies 7 ·
Replies
7
Views
3K
Replies
3
Views
2K
  • · Replies 2 ·
Replies
2
Views
1K