C++ standard says:
The function
main
shall not be used within a program.
Also:
Recursive calls are permitted, except to the
main
function.
At the same time C allows such a usage of main
according to this answer. I found a comment under that answer that says the following:
The simplest implementation of global constructors (without special support from the OS and underlying C runtime entry code) is for the C++ compiler to generate a function call at the beginning of main (__main is a common name for it) which calls all the global constructors. Having global objects be reconstructed every time main gets called recursively would be a rather bad thing... :-)
It makes sense, but I've tried the following code:
#include <cstdio>
struct S {
S() { std::puts("S ctor"); }
~S() { std::puts("S dtor"); }
};
S s;
int main() {
static int count = 0;
count++;
if (count <= 10) {
std::printf("%d ", count);
return main();
}
std::puts("");
}
in clang, gcc, msvc. All of these compilers print same output:
S ctor
1 2 3 4 5 6 7 8 9 10
S dtor
So the global s
object was contructed only once despite recursive call of main
. Yes, I know what are undefined/unspecified/implementation-defined behaviour mean. But would someone explain (or even demonstrate by code for any available in internet compiler) in more details why using a main
function in the C++ program is forbidden and may lead to unexpected results in particular?