Before You Say Goodbye . . .

The standard C library contains a lot of interesting and unusual routines. Some can really put the fun into function. One of them I’ve rarely used, but which can be extremely handy, is atexit().

The atexit() function is one of those weirdo functions that uses another function as its argument. (I’ll explain how that works in a future Lesson.) The function that atexit() references is run automatically whenever your program exits, either by returning from the main() function or at any point by calling exit(). Either way, whichever function atexit() registered is called before the program terminates.

Sounds fun, right?

Here’s a silly example:

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

void bye(void);

int main()
{
    atexit(bye);

    puts("Happy Little Program");
    puts("Massive processing completed!");

    return(0);
}

void bye(void)
{
    puts("So long, sailor!");
}

The atexit() function (Line 8) registers the bye() function to be run when the program quits. So when the return statement is hit at Line 13, the bye() function is called. Here’s sample output:

Happy Little Program
Massive processing completed!
So long, sailor!

The atexit() can be called multiple times to have a spate of functions run when the program quits. The functions are run in the reverse order they’re called; so the first atexit() specifies the last function run. Here’s a modification to the sample code that illustrates that behavior:

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

void bye(void);
void solong(void);

int main()
{
    atexit(bye);
    atexit(solong);

    puts("Happy Little Program");
    puts("Massive processing completed!");

    return(0);
}

void bye(void)
{
    puts("So long, sailor!");
}

void solong(void)
{
    puts("Whew! That was rough.");
}

The bye() function is registered first by atexit() in Line 9. It’s called last.

The solong() function is registered next, so it’s called before bye().

Here’s sample output:

Happy Little Program
Massive processing completed!
Whew! That was rough.
So long, sailor!

A more practical example of how to use atexit() would be in a large program where some necessary cleanup would be performed. Rather than try to snake all the return calls and exit() routines together, simply register the cleanup functions by using atexit(). Then no matter where the program chooses to bail, you’ll know that things are taken care of.

Leave a Reply