Home Is it possible to call main() recursively?
Post
Cancel

Is it possible to call main() recursively?

(Some useless info, I guess)

Long time ago I was reading “questions for C++ interview” and met this question: “it is possible to call the main() function from the program, that is, recursively?”

1
2
3
4
5
6
7
8
int main() {
    int n;
    std::cin >> n;
    if (n != 0) {
        return main();
    }
    return 0;
}

Well, what’s the purpose of doing this why one couldn’t do this?

In all environments, which I’m aware of, the main() function is not the actual entry point - firstly they call a compiler-generated function that initializes the global variables. The main() doesn’t differ from other function from this point of view.

The main() function linkage is implementation-define (link to the Standard): the name of the function doesn’t get mangled. Also the Standard mentions that one shouldn’t call the main() function inside the program.

The Standard clarifies that recursivelly calling main() is prohibited (link to the Standard).

But every modern compiler compiles such code successfully! They could emit a warning if it’s compiled with the -Wmain flag: link to godbolt.

Therefore the answer to the question is as follows: it is prohibited to call main() recursively, but the compiler will compile such code without complaints, if you don’t use flags like -Wmain or -pedantic.

This post is licensed under CC BY 4.0 by the author.

Your own compiler - do it yourself ⚙️🛠

📚 Book review: "C++20: Get the Details" (2021)