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

独自空忆成欢 提交于 2019-11-26 11:21:23

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.

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.

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.)

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. ]

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]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!