Programs can be explicitly exited using std::exit function. This does normal termination of the program.

std::exit takes a return status code as an argument. This status code determines if the program is succeeded or failed in its operation. Status code 0 means that the program succeeded otherwise failed.

For example,

#include <cstdlib>
#include "../helpers/stdout.h"
 
int main(int argc, char const *argv[])
{
 
    print("Starting");
 
    std::exit(0);
    print("Finished");
    return 0;
}
 

std::exit function also does some extra task of cleaning such as destroying static objects, closing files etc. However, it is always a good practice to do clean up explicitly. We can have a cleanup function that closes the opened files and does other types of cleanups.

We can use std::atexit function to hook tasks that we would want to perform when std::exit is called. We can use this function to hook cleanup tasks.

For example,

#include <cstdlib>
#include "../helpers/stdout.h"
 
void cleanup()
{
    print("Closing opened files.");
    print("Cleaning up other things");
}
 
int main(int argc, char const *argv[])
{
 
    std::atexit(cleanup);
    print("Starting");
 
    std::exit(1);
    print("Finished");
    return 0;
}

We can call std::atexit as many times as we want. The order of function call will be on last come first serve basis.

References

  1. https://www.learncpp.com/cpp-tutorial/halts-exiting-your-program-early/