The C++ <cstdlib> exit function terminates the program normally.The declaration of the function is shown below.
|void exit(int status);|
status -The status code returned to the host(Operating system).
The ‘exit’ function is used to terminate the program safely.It acts like a ‘break’ statement which throws the chain of the execution out of the loop statement.In fact the sole purpose of ‘exit’ is to terminate the program at any time safely,why safely? the reason is provided below.
Some points to note :
In calling the ‘exit’ function before the program terminates,
i) All the objects of the current thread(currently executing code) are destroyed.All the functions registered by calling ‘atexit’ is called in reverse order of their registration.If the control leaves the registered function because no handler is provided for the exception then ‘terminate()’ function shall be called.
ii) All the open stream with unwritten buffer is flush,all open stream is closed and if there is any temporary file created by ‘tmpfile()’ it is removed.
iii) After all the above process are carried out,if the status -the argument value- is EXIT_SUCCESS or 0 implementation-defined form of the status successful termination is returned.If status is EXIT_FAILURE an implementation-defined form of unsuccessful termination is returned.
v)If there is any functions registered using ‘atexit’ after the ‘exit’ function,the registered function is not called or the behavior is implementation-defined.
Link :C++ cstdlib atexit
int main( )
func( 3 );
A more exhaustive code example using ‘exit’ is given below.
using namespace std;
void undefinedResult( )
cout<< “Undefined result \n”;
int main( )
double value , result ;
cout<< “Enter any value to compute the value of ‘log1p’ \n”;
cin>> value ;
result=log1p( value );
if( result==INFINITY | result==-INFINITY ) //checks if the ‘result’ equals infinity
atexit( undefinedResult ) ;
cout<< “log1p( “<< value << ” )=” << result ;
Enter any value to compute the value of ‘log1p’
log1p(-1) gives ‘-∞’,hence the result.You can check the program yourself for other values.
Link : C++ cmath log1p