Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading