Can anybody tell what’s the problem of the code below?
int main () {
return main();
}
I tested, it compiles correctly. It’s running forever. Anymore trick behind the scene?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
TLDR: Calling
mainresults in undefined behavior.There seems to be confusion about the terminology used in the standard, and the implications that has for the programmer and compiler.
Firstly, the standard alone determines everything about the C++ language. If your particular version of a particular compiler allows some particular action, that has no bearing on whether or not that action is legal. For the remainder of the post, I’m referring to the ISO03 standard.
So to quote once again, the standard says in §3.6.1.3:
Additionally, §3.2 defines “used” as:
This means that once the program begins executing,
mainshould never be entered again. That means programmers cannot callmain, that means the compiler cannot insert another call tomain(why it would, who knows), you cannot take the address of main and call that, etc. You cannot even have the potential of callingmain.The only call to
mainshould be by the run-time library the program is running on; all other calls invoke undefined behavior. (Which means anything could happen!)Now onto compiler behavior:
A diagnosable rule is defined as (§1.4.1):
In our case, §3.6.1.3 defines a diagnosable rule. Here’s what compilers should do according to §1.4.2:
So compilers are not required to enforce rules. All compilers have to do is take well-formed programs (§1.3.14) and turn them into an executable program. A compiler is free to warn, error, etc. however it likes, as long as it does not conflict with the language. It is required to display a message in our particular case, according to the second clause.
For this particular problem, on gcc the
-pedanticoption will warn about the illegality of callingmainwithin the program. Visual Studio will not warn about callingmain, but on any warning level (greater than 0) it will warn about the recursive nature of the program.What does all this mean in terms of the answers you should expect? It means it’s completely meaningless to try and define with certainty what the code snippet posted will do. Calling
mainresults in undefined behavior, and trying to define undefined behavior is obviously a lost cause. The only honest answer anyone can give to “what happens when I callmain?” is “Anything.”I hope this clears things up.