Title here
Summary here
Here’s an idiomatic C++ example that demonstrates the concept of program exit:
#include <iostream>
#include <cstdlib>
void cleanup() {
std::cout << "Cleanup function called." << std::endl;
}
int main() {
// Register cleanup function
std::atexit(cleanup);
// This will be printed
std::cout << "Exiting program..." << std::endl;
// Exit with status 3
std::exit(3);
// This line will never be reached
std::cout << "This won't be printed." << std::endl;
}
This C++ program demonstrates how to exit a program with a specific status code. Let’s break it down:
We include necessary headers: <iostream>
for input/output operations and <cstdlib>
for the std::exit()
function.
We define a cleanup()
function that will be called when the program exits normally.
In the main()
function:
cleanup()
function using std::atexit()
. This function will be called when the program exits normally.std::exit(3)
to immediately terminate the program with exit status 3.cout
statement will never be executed because std::exit()
terminates the program immediately.To compile and run this program:
exit_example.cpp
.$ g++ -std=c++11 -o exit_example exit_example.cpp
$ ./exit_example
Exiting program...
Cleanup function called.
$ echo $?
3
Key points to note:
main()
to indicate the exit status. However, using std::exit()
gives you more control and allows you to exit from any point in your program.std::atexit()
are called in the reverse order of their registration when the program exits normally or when std::exit()
is called.std::exit()
does not unwind the stack, so destructors for automatic objects are not called. If you need stack unwinding, consider using std::quick_exit()
or throwing an exception and catching it in main()
.This example demonstrates how to properly exit a C++ program with a specific status code and how to set up cleanup functions that run on program exit.