Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my C++ compiler allow recursive calls to main? [duplicate]

Possible Duplicate:
Is it legal to recurse into main() in C++?

#include <iostream>
using namespace std;

int main() {
  static int var = 5;
  std::cout << --var;
  if(var)
    main();
}

gcc compiles the code http://ideone.com/lIp3A . I know that main cannot be used inside main in C++. How come this code compiles?

like image 554
PaulNathan Avatar asked Dec 04 '22 09:12

PaulNathan


1 Answers

The code is ill-formed because it violates the shall construct of §3.6.1.3

§3.6.1.3 says :

The function main shall not be used within a program.


The shall construct

A diagnosable rule is defined as (§1.4.1):

The set of diagnosable rules consists of all syntactic and semantic rules in this International Standard except for those rules containing an explicit notation that “no diagnostic is required” or which are described as resulting in “undefined behavior.”

§3.6.1.3 defines a diagnosable rule.

According to §1.4.2:

— If a program contains no violations of the rules in this International Standard, a conforming implementation shall, within its resource limits, accept and correctly execute that program.

— If a program contains a violation of any diagnosable rule, a conforming implementation shall issue at least one diagnostic message, except that

— If a program contains a violation of a rule for which no diagnostic is required, this International Standard places no requirement on implementations with respect to that program.


Conclusion

A compiler is free to do whatever it wants to do. Try the same code on Comeau Online (a more conforming compiler). I get this error "function "main" may not be called or have its address taken"

like image 114
Prasoon Saurav Avatar answered Jan 04 '23 22:01

Prasoon Saurav