An example of atexit in C

This is an example C program demonstrating atexit. The function atexit registers a function to be called at the exit of a program. The function must have prototype void (*) (void). More than one function may be registered with atexit. If more than one function is registered, successive functions are called from the most recently registered to the first registered.

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

int i;

void check_a (void)
{
    i++;
    printf ("Check A: %d\n", i);
}

void check_b (void)
{
    i++;
    printf ("Check B: %d\n", i);
}

int main ()
{
    check_a ();
    atexit (check_a);
    check_b ();
    atexit (check_b);
    printf ("Exiting.\n");
    return 0;
}

(download)

The output of the example looks like this:

Check A: 1
Check B: 2
Exiting.
Check B: 3
Check A: 4


Copyright © Ben Bullock 2009-2023. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (benkasminbullock@gmail.com) or use the discussion group at Google Groups. / Privacy / Disclaimer