Problem with implicit recursion

In the case of the implicit recursion, the issue of an infinite function call may occur. Here is a case where implicit recursion can cause the problem:

C++




#include <iostream>
 
using namespace std;
 
void func2();
void func1();
 
void func1() {
  cout << "This is the first function" << endl;
  func2();
}
 
void func2() {
  cout << "This is the second function" << endl;
  func1();
}
 
int main() {
  func1();
 
  return 0;
}


Java




/*package whatever //do not write package name here */
 
import java.io.*;
 
class GFG {
   
      static void func1(){
        System.out.println("This is the first function");
          func2();
    }
   
      static void func2(){
        System.out.println("This is the second function");
          func1();
    }
   
    public static void main (String[] args) {
        func1();
    }
}
 
// This code is contributed by lokeshmvs21.


Python3




def func1():
    print("This is the first function")
    func2()
 
def func2():
    print("This is the second function")
    func1()
 
func1()


C#




using System;
 
public class GFG {
 
    static void func1()
    {
        Console.WriteLine("This is the first function");
        func2();
    }
 
    static void func2()
    {
        Console.WriteLine("This is the second function");
        func1();
    }
 
    static public void Main()
    {
 
        // Code
        func1();
    }
}
 
// This code is contributed by lokesh.


Javascript




// Define func2
function func2() {
  console.log("This is the second function");
  // Call func1 inside func2
  func1();
}
 
// Define func1
function func1() {
  console.log("This is the first function");
  // Call func2 inside func1
  func2();
}
 
// Call func1 from main
func1();


Output: 

This is the first function
This is the second function
This is the first function
This is the second function
...
...

In this example, the func1() function calls func2(), which then calls func1() once again.

What is Implicit recursion?

Similar Reads

What is Recursion?

Recursion is a programming approach where a function repeats an action by calling itself, either directly or indirectly. This enables the function to continue performing the action until a particular condition is satisfied, such as when a particular value is reached or another condition is met....

What is Implicit Recursion?

A specific sort of recursion called implicit recursion occurs when a function calls itself without making an explicit recursive call. This can occur when a function calls another function, which then calls the original code once again and starts a recursive execution of the original function. This can sometimes be difficult to spot and can lead to unintended behavior if not handled carefully....

Problem with implicit recursion:

...

Steps to avoid this issue:

...