How do I make a C++ console program exit?

rectangletangle picture rectangletangle · Oct 28, 2010 · Viewed 127.1k times · Source

Is there a line of code that will terminate the program?

Something like python's sys.exit()?

Answer

James McNellis picture James McNellis · Oct 28, 2010

While you can call exit() (and may need to do so if your application encounters some fatal error), the cleanest way to exit a program is to return from main():

int main()
{
    // do whatever your program does

} // function returns and exits program

When you call exit(), objects with automatic storage duration (local variables) are not destroyed before the program terminates, so you don't get proper cleanup. Those objects might need to clean up any resources they own, persist any pending state changes, terminate any running threads, or perform other actions in order for the program to terminate cleanly.