How do I make a C++ console program exit?
Yes! exit()
. It's in <cstdlib>
.
There are several ways to cause your program to terminate. Which one is appropriate depends on why you want your program to terminate. The vast majority of the time it should be by executing a return statement in your main function. As in the following.
int main()
{
f();
return 0;
}
As others have identified this allows all your stack variables to be properly destructed so as to clean up properly. This is very important.
If you have detected an error somewhere deep in your code and you need to exit out you should throw an exception to return to the main function. As in the following.
struct stop_now_t { };
void f()
{
// ...
if (some_condition())
throw stop_now_t();
// ...
}
int main()
{
try {
f();
} catch (stop_now_t& stop) {
return 1;
}
return 0;
}
This causes the stack to be unwound an all your stack variables to be destructed. Still very important. Note that it is appropriate to indicate failure with a non-zero return value.
If in the unlikely case that your program detects a condition that indicates it is no longer safe to execute any more statements then you should use std::abort(). This will bring your program to a sudden stop with no further processing. std::exit() is similar but may call atexit handlers which could be bad if your program is sufficiently borked.
#include <cstdlib>
...
exit( exit_code );
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.