Can main function call itself in C++?


The main() function can call itself in C++. This is an example of recursion as that means a function calling itself. A program that demonstrates this is given as follows.

Example

 Live Demo

#include<iostream>
using namespace std;
int main() {
   static int x = 1;
   cout << x << " ";
   x++;
   if(x == 11) {
      return 0;
   }
   main();
}

Output

The output of the above program is as follows.

1 2 3 4 5 6 7 8 9 10

Now, let us understand the above program.

The variable x is a static variable in main(). Its value is displayed and then it is incremented. Then the if statement is used to provide a means to end the program as otherwise it would call itself infinitely. The program ends when the value of x is 11. Finally, the function main() calls itself using the function call main(). The code snippet for this is given as follows.

int main() {
   static int x = 1;
   cout << x << " ";
   x++;
   if(x == 11) {
      return 0;
   }
   main();
}

Updated on: 26-Jun-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements