A tail recursion happens when the recursive call is executed at the end by the function. It's considered better than the non-tail recursion code we developed previously because the compiler can optimize the code better. Since the recursive call is the last statement that is executed by the function, there is nothing more to do in this function. The result is that the compiler does not need to save the current function's stack frame. Let's see the following tail_recursion.cpp code implementing tail recursion:
/* tail_recursion.cpp */
#include <iostream>
using namespace std;
void displayNumber(long long n)
{
// Displaying the current n value
cout << n << endl;
// The last executed statement
// is the recursive call
displayNumber(n + 1);
}
auto main() -> int
...