Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive call on main C++ [duplicate]

Tags:

c++

Possible Duplicate:
Can main function call itself in C++?

I found this problem very interesting but illusive a bit. Question 6.42 C++ how to program by Dietel "Can main be called recursively on your system? write a program containing a function main. Include Static local variable count and initialize to 1. Post-increment and print the value of count each time main is called. Compile your program. What happens ?

I wrote the program as below but instead I made the recursion stops after 10 times as if I were to keep it running it will stops at a value around 41000.

my question: how is it legal to call recursively main function in c++, should this program be executed to stack over flow or memory fault, etc.. ? Please explain.

#include <iostream>
using namespace std;
int main()
{
       static int count = 0;
       count++;
       if(count <= 10) {
                cout << count << endl;
                return main(); //call main
                }//end if

       system("pause");
       return 0;//successful completion
}//end main

thank you

like image 450
Sinan Avatar asked Jul 05 '12 17:07

Sinan


1 Answers

How is it legal to call the main() function recursively in C++

It is not legal. The C++ language standard states that "The function main shall not be used within a program" (C++11 §3.6.1/3). Calling the function is a form of "use."

Any program that calls main() exhibits undefined behavior (technically, such a program is ill-formed because the rule being violated is a diagnosable semantic rule, though I'd be surprised if most compilers rejected the program). Note that this does not prevent the runtime infrastructure that starts your program from calling the main() function.

like image 197
James McNellis Avatar answered Sep 25 '22 01:09

James McNellis