- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
#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(); }
Advertisements