Exit in C++
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 thestd::exit()function.We define a
cleanup()function that will be called when the program exits normally.In the
main()function:- We register the
cleanup()function usingstd::atexit(). This function will be called when the program exits normally. - We print a message indicating that the program is exiting.
- We call
std::exit(3)to immediately terminate the program with exit status 3. - The last
coutstatement will never be executed becausestd::exit()terminates the program immediately.
- We register the
To compile and run this program:
- Save the code in a file named
exit_example.cpp. - Open a terminal and navigate to the directory containing the file.
- Compile the code:
$ g++ -std=c++11 -o exit_example exit_example.cpp- Run the program:
$ ./exit_example
Exiting program...
Cleanup function called.- Check the exit status:
$ echo $?
3Key points to note:
- Unlike in some other languages, C++ allows you to return an integer from
main()to indicate the exit status. However, usingstd::exit()gives you more control and allows you to exit from any point in your program. - Functions registered with
std::atexit()are called in the reverse order of their registration when the program exits normally or whenstd::exit()is called. std::exit()does not unwind the stack, so destructors for automatic objects are not called. If you need stack unwinding, consider usingstd::quick_exit()or throwing an exception and catching it inmain().
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.
Comments powered by Disqus