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

C++, when I put return 0 in a function and use the function main, the system still keep working

My idea is to write a exit function to terminate the whole system, so I wrote the function int exit_c(), and put it in the while loop, but it seems that the system keeps working.

int main() {

    while (true) {
        exit_c();
    }

    system("pause");
    return 0;
}
int exit_c() {
    cout << "close" << endl;
    system("pause");
    return 0;
}

console result

But when I replace the exit_c() in while loop, which just system("pause") and return 0, the system will terminate.

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

int main() {

    while (true) {
        system("pause");
                return 0;
    }

    system("pause");
    return 0;
}

>Solution :

return returns from a function. Hence, you cannot simply copy the code in the function to replace its call and expect the code to behave the same. The return 0; which before returned from exit_c now returns from main. Thats the difference you see.

On a related note: return 0; in main is implicit. You can remove it from your code when it is the last statement.

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