Alex Rivera | Logout

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

Asked 2010-12-23T12:07:29.843
46

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?

Edit
Report

1 Answer

37

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.

answered 2010-12-23T14:01:35.823

Your Answer