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:

  1. We include necessary headers: <iostream> for input/output operations and <cstdlib> for the std::exit() function.

  2. We define a cleanup() function that will be called when the program exits normally.

  3. In the main() function:

    • We register the cleanup() function using std::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 cout statement will never be executed because std::exit() terminates the program immediately.

To compile and run this program:

  1. Save the code in a file named exit_example.cpp.
  2. Open a terminal and navigate to the directory containing the file.
  3. Compile the code:
$ g++ -std=c++11 -o exit_example exit_example.cpp
  1. Run the program:
$ ./exit_example
Exiting program...
Cleanup function called.
  1. Check the exit status:
$ echo $?
3

Key points to note:

  • Unlike in some other languages, C++ allows you to return an integer from 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.
  • Functions registered with 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.