atexit C Library Function

The stdlib C Library function atexit registers the function pointed to by func to be called when the program terminates. Upon normal termination of the program, function pointed by func is automatically called without arguments. You can register your termination function anywhere in program.

You can call atexit function more than once, they are all executed in reverse order of their call(the last function to be registered will be the first function to be called).

Function prototype of atexit

int atexit(void (*func)(void));
  • func : It is a pointer to a function to be called at the termination of the program. This function must not return any value and take no arguments.

Return value of atexit

This function returns zero value, if the function was successfully registered, otherwise a non-zero value if unsuccessful.

C program using atexit function

The following program shows the use of atexit function to call a function at the time of program termination.

atexit C Library Function

#include <stdio.h>
#include <stdlib.h>
 
void myFunction(){
    printf("Program end, Bye Bye\n");
    getch();
}
 
int main(){
    printf("Program start\n");
    atexit(myFunction);  
    return 0;
}

Output

Program start
Program end, Bye Bye