- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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(); }
- Related Articles
- How to call the main function in C program?
- C/C++ Function Call Puzzle?
- Differentiate between int main and int main(void) function in C
- A C/C++ Function Call Puzzle?
- Can main() be overloaded in C++?
- How we can call Python function from MATLAB?
- Referring JavaScript function from within itself
- JavaScript Function Call
- How to call a JavaScript function from C++?
- How to Call a Lua function from C?
- Is there any way I can call the validate() function outside the initValidation() function in JavaScript?
- How to call a parent class function from derived class function in C++?
- How to call a virtual function inside constructors in C++?
- When do I need to call the main loop in a Tkinter application?
- How to call a function in JavaScript?

Advertisements