atexit() function in C/C++

The atexit() function in C is used to register functions that will be called automatically when the program terminates normally. These registered functions are executed in reverse order (LIFO - Last In, First Out) after the main function completes but before the program ends. This function is declared in the <stdlib.h> header file.

Syntax

int atexit(void (*function_name)(void))

Parameters:

  • function_name − A pointer to the function that will be called at program termination. The function must take no parameters and return void.

Return Value: Returns 0 on success, or a non-zero value if the function cannot be registered.

Example: Basic Usage of atexit()

This example demonstrates how atexit() registers functions to be called at program termination −

#include <stdio.h>
#include <stdlib.h>

void func1(void) {
    printf("Exit of function 1\n");
}

void func2(void) {
    printf("Exit of function 2\n");
}

int main() {
    atexit(func1);
    printf("Starting of main()\n");
    atexit(func2);
    printf("Ending of main()\n");
    return 0;
}
Starting of main()
Ending of main()
Exit of function 2
Exit of function 1

Example: Multiple Functions with atexit()

This example shows how multiple functions are executed in reverse order −

#include <stdio.h>
#include <stdlib.h>

void cleanup1(void) {
    printf("Cleanup function 1 called\n");
}

void cleanup2(void) {
    printf("Cleanup function 2 called\n");
}

void cleanup3(void) {
    printf("Cleanup function 3 called\n");
}

int main() {
    printf("Registering cleanup functions...\n");
    
    atexit(cleanup1);
    atexit(cleanup2);
    atexit(cleanup3);
    
    printf("Main function ending normally\n");
    return 0;
}
Registering cleanup functions...
Main function ending normally
Cleanup function 3 called
Cleanup function 2 called
Cleanup function 1 called

Key Points

  • Functions registered with atexit() are called in reverse order of registration (LIFO).
  • The registered functions are called only during normal program termination, not when the program is terminated abnormally.
  • Up to 32 functions can typically be registered with atexit() (implementation-dependent).
  • Registered functions must have void return type and take no parameters.

Conclusion

The atexit() function provides a clean way to register cleanup functions that execute automatically when a program terminates normally. Functions are executed in reverse order of registration, making it useful for resource cleanup and finalization tasks.

Updated on: 2026-03-15T09:57:38+05:30

461 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements