Call main() itself in c++?

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'

Leave a Comment