Open In App

How to go to main stack?

Last Updated : 16 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

What is the main() function?

The function named “main” is a special function. It is the function called when a code is run. The execution of all programs begin with the main() function irrespective of where the function is actually located within the code.

How to go to the main() stack from a function?

At any stack or recursion of our program, we can simply call the main() function to go to the main stack easily. It can be demonstrated by a small program

Implementation:

C++




// C++ implementation
 
#include <bits/stdc++.h>
using namespace std;
 
// Declaring the function
void fun();
 
// Driver code
int main()
{
    // Calling the function fun()
    cout << "Inside main" << endl;
    fun();
    return 0;
}
 
void fun()
{
    static int key = 2;
    if (key == 0)
        return;
    key--;
    cout << "Inside fun" << endl;
 
    // Calling the main() function to go
    // back to the main stack
    main();
}


Java




/*package whatever // do not write package name here */
 
import java.io.*;
 
class GFG {
 
    static int key = 2;
    static void fun()
    {
        if (key == 0)
            return;
        System.out.println("Inside fun");
        key--;
 
        // Calling the main() function to go back to the
        // main stack
        GFG.main(null);
    }
 
    // Driver  code
    public static void main(String[] args)
    {
        System.out.println("Inside main");
 
        // Calling the function fun()
        fun();
        return;
    }
}


C#




using System;
 
public class GFG {
 
  static int key = 2;
  static void fun()
  {
    if (key == 0)
      return;
    Console.WriteLine("Inside fun");
    key--;
 
    // Calling the main() function to go back to the
    // main stack
    GFG.Main();
  }
 
  static public void Main()
  {
 
    // Code
    Console.WriteLine("Inside main");
 
    // Calling the function fun()
    fun();
  }
}
 
// This code is contributed by lokesh.


Output

Inside main
Inside fun
Inside main
Inside fun
Inside main

Whenever we are calling the main() function again it again starts executing the program



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads