Search code examples
c++recursionprogram-entry-point

The c++ standard documentation says a program shall not call the main function, but I did


It explicitly says in the c++ standard documentation that a program may not call main. Yet I wrote a program that calls main and works perfectly fine, why is that? The code:


#include<iostream>

static int counter = 0;

int main(){
    counter++;
    std::cout << counter << " It works" << std::endl;
    
    while(counter < 10){
        main();
    }

    return 1;
}

It prints to console "It works" 10 times. According to the standard documentation, this should not work, yet it works. What's going on?


Solution

  • basic.start.main/3: The function main shall not be used within a program.

    Violating this rule makes your program have undefined behavior - which means that the program can do pretty much anything. It may even do what you wanted it to do or appear to do what you wanted but have devastating side effects, so avoid having undefined behavior in your programs.

    Regarding the lack of diagnostic messages: I suspect that some compilers, like g++, actually support calling main as an extension. I had to turn on -pedantic or -pedantic-errors to get the diagnostic message "ISO C++ forbids taking address of function '::main' [-Wpedantic]"