Three ways to terminate c++ program

 There are three methods for terminating a C++ program. 

  • call the exit function
  • call the abort function
  • and the return statement

exit function

A C++ program is terminated using the exit function, which is defined in
<stdlib.h>. As the program's return code or exit code, the value
specified as an input to exit is returned to the operating system. A return
code of zero, by convention, indicates that the program was successful. The
constants EXIT FAILURE and EXIT SUCCESS, both specified in <stdlib.h>,
can be used to indicate whether your application succeeded or failed.

Calling the exit function with the return value as its argument is equal to
issuing a return statement from the main function.

abort function

A C++ program is terminated with the abort function, which is also declared in
the standard include file <stdlib.h>. The distinction between exit and
abort is that exit allows for C++ run-time termination (global object
destructors are called), whereas abort immediately ends the program. For
initialised global static objects, the abort function avoids the normal
destruction process. It also skips any particular processing that the atexit
function has provided.

atexit function

Use the atexit function to define actions that will be performed before the
program exits.
No global static objects created before calling atexit are
deleted before the exit-processing method is called. 

return statement in main

Calling the exit function is functionally equivalent to issuing a return
statement from main. Consider the following scenario:

// return_statement.cpp
#include 
<stdlib.h>
int main()
{
exit( 3 );
return 3;
} 

The preceding example's exit and return statements are functionally identical. C++ normally requires functions with return types other than void to return a value. The main function is an exception; it can be terminated without a return statement. In that case, it returns to the invoking process an implementation-specific value. You can specify a return value from main using the return statement. 

Destruction of static objects

Static objects are destroyed in the reverse order of their initialization when you call exit or execute a return statement from main (after the call to atexit if one exists).

Share this Post

Leave a Reply

Your email address will not be published. Required fields are marked *