Call main() itself in c++?

Solution 1:

Is it allowed in "C++"? No.

In practice, can you call main()? Yes.

Whatever the C++ Standard says, that doesn't stop the Linux g++ compiler from compiling code with main() in main().

#include <cstdlib>
#include <iostream>
using namespace std;
int main()
{
 int y = rand() % 10; // returns 3, then 6, then 7
 cout << "y = " << y << endl;
 return (y == 7) ? 0 : main();
}

Which lets us do:

 > g++ g.cpp; ./a.out
 y = 3
 y = 6
 y = 7

Looking in to the assembly, we see that main is called just like any other function would be:

main:
        ...
        cmpl    $7, -12(%rbp)
        je      .L7
        call    main
        ...
.L7:
        ...
        leave
        ret

Not that this behavior is guaranteed, but it looks like g++ doesn't seem to really care about the standard, apart from this sarcastic warning with -pedantic

g.cpp:8: error: ISO C++ forbids taking address of function '::main'

Solution 2:

The C++ Standard says that you may not call main() from your own code. As for getting the name of the current function, you could use the __FUNCTION__ macro, but once again this is not standard:

#include <iostream>
using namespace std;

void foo() {
   cout << __FUNCTION__ << endl;
}

int main() {
   foo();
}

should print "foo" or something similar if __FUNCTION__ is supported.

Solution 3:

If a specific implementation allows this, it is not behaving correctly(a). The standard state quite explicitly in C++14, 3.6.1 Main function /3:

The function main shall not be used within a program.


(a) Keep in mind that many implementations follow some parts of the standard loosely, preferring power over strictness. That can have the unfortunate side effect that your code may not be portable to other compilers or even other versions of the same compiler.

Many implementations will also allow you to take the stricter view, such as using g++ -std=c++11 -Werror=pedantic which catches the particular issue bought up in this question, as well as quite a few others. It is that "mode" of translation that allows implementations to claim to be compliant with the standard, as per 1.4 Implementation compliance:

If a program contains a violation of any diagnosable rule ..., a conforming implementation shall issue at least one diagnostic message.

You'll see it's still quite possible to allow the code to compile and run in that case, since "diagnostic message" can mean a warning rather than an error.