C programming atexit stdlib.h


In C programming the <stdlib.h> atexit function registers the function pointed by the parameter and call it at normal program termination.The declaration of the function is shown below.

int atexit(void (*func )(void)) noexcept;

Parameters:
(*func )(void) -A pointer to function which does not return any value and also does not accept any argument (except void type).

Return type
int – Returns 0 if it succeeds,else it returns some non-zero value.

Some points to note:

i) This function is only called if the program terminates normally,if ‘abort’ is called this function is not called.And also this function does not pass any exception.

Link:C abort stdlib.h

ii) If ‘atexit’ is called after the call to ‘exit’ function it is not specified whether the function is called.

iii) The implementation shall support the registration of at least 32 functions.

iv) If the function accept any argument or return any type other than the ‘void’ type you will get an error.

v) If many functions are registered then the functions are called in the reverse order of their registration.This simply means the function that appear first as the ‘atexit’ parameter is called last.A code example for this case is provided below.

vi) The ‘atexit’ does not introduce data races.

Code example

void func( )
{
printf(“func called \n”) ;
}

int main( )
{
printf(“Calling atexit” );

atexit( func );

getchar( );
return 0;
}

Output

Calling atexit
func called

You can see the function ‘func’ is called when the program terminates.





A code example which determine the order of calling the registered functions is given below.

Code example

void func1( ) { printf(“func1 called \n”); }

void func2( ) { printf(“func2 called \n”); }

int main( )
{
atexit( func1 );

atexit( func2 );

getchar( );
return 0;

Output ,

func2 called
func1 called

func1 is registered after func1 but called earlier to func1.


Related links

->C exit stdlib.h