Is it legal to recurse into main() in C++? [duplicate]

I read that the C++ standard forbids recursion in main(), but g++ compiles the following code without complaint:

int main()
{
    main();
}

Can anyone clarify this?


Solution 1:

According to the standard in 3.6.1/3, it's not :

The function main shall not be used (3.2) within a program

The definition of used being :

An object or non-overloaded function is used if its name appears in a potentially-evaluated expression.

Solution 2:

I'll do the fish and explain why this is verboten. Before a C or C++ program can start running, the CRT has to be initialized first. Open stdin/out/err, call initializers, that sort of thing. There are two basic strategies to get this done, a heavy platform implementation detail.

  • The program's start address points to the CRT init function, which eventually calls main(). Common on full-featured operating systems that have a fancy loader which can support arbitrary sections in the executable image.

  • The compiler injects code into the main() function that calls the CRT initialization function. The start function is always main(). Common on embedded platforms with limited loader capabilities. Recursing main() is now a problem, the CRT startup code will be called again with an unpredictable stack state.

Solution 3:

The claim here is that it is indeed specifically forbidden:

Well, the standard states:

3.6.1.3
"The function main shall not be used within a program."

5.2.2.9
"Recursive calls are permitted, except to the function named main"

You can, of course, do this:

int main(int argc, char* argv[]) {
    return foo(argc, argv);
}
int foo(int argc, char* argv[]) {
    if (some_condition) {
        return foo(argc, argv);
    }
    return 0;
}

(Note I added a get-out clause. I can't even hypothetically code infinite recursion, it repeats on me.)

Solution 4:

It is not legal. Read 3.6.1-3 :

The function main shall not be used (3.2) within a program. The linkage (3.5) of main is implementation-defined. A program that declares main to be inline or static is ill-formed. The name main is not otherwise reserved. [Example: member functions, classes, and enumerations can be called main, as can entities in other namespaces. ]

Solution 5:

Other people have addressed the standards part. However, I'd like to note that g++ (at least 4.6.2) will reject this if you use -pedantic-errors with at least one of these errors (depending on main signature):

error: ISO C++ forbids calling ‘::main’ from within program [-pedantic]
error: ISO C++ forbids taking address of function ‘::main’ [-pedantic]