Write a C program to check the atexit() function

The atexit() is a function that allows the user to register a function that has to be called when the program terminates normally. These registered functions are called in the reverse order of their registration.

It is a predefined function that is included in the stdlib.h header file.

Syntax

int atexit(void (*function)(void));

Parameters:

  • function − Pointer to a function that takes no parameters and returns no value.

Return Value: Returns 0 on success, non-zero on failure.

Example 1: Basic Usage

This example demonstrates how atexit() calls registered functions in reverse order −

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

void welcome(void) {
    printf("Welcome to New, ");
}

void world(void) {
    printf("World<br>");
}

int main() {
    /* Register functions with atexit - called in reverse order */
    atexit(world);
    atexit(welcome);
    
    printf("Main function executing...<br>");
    return 0;
}
Main function executing...
Welcome to New, World

Example 2: Multiple Function Registration

This example shows how multiple functions are executed in LIFO (Last In, First Out) order −

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

void first(void) {
    printf("This is a beautiful, ");
}

void second(void) {
    printf("Wonderful life<br>");
}

void cleanup(void) {
    printf("Cleaning up resources...<br>");
}

int main() {
    /* Register functions - they execute in reverse order */
    atexit(cleanup);
    atexit(second);
    atexit(first);
    
    printf("Program is running...<br>");
    return 0;
}
Program is running...
This is a beautiful, Wonderful life
Cleaning up resources...

Key Points

  • Functions registered with atexit() are called only on normal program termination.
  • Up to 32 functions can be registered (implementation-dependent).
  • Functions are called in reverse order of registration (LIFO).
  • These functions cannot receive parameters or return values.

Conclusion

The atexit() function is useful for cleanup operations and resource management. It ensures that registered functions execute automatically when the program terminates normally, providing a clean way to handle program shutdown tasks.

Updated on: 2026-03-15T13:48:03+05:30

605 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements