Categories
c programming tips and tricks

Call Functions at Program Termination

Did you know about the atexit() API? This C API is used to register functions which can get automatically called when the program finishes its execution.

For example –

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

void foo(void)
{
    printf("Goodbye Foo!\n");
}

void bar(void)
{
    printf("Goodbye Bar!\n");
}

int main(int argc, wchar_t* argv[])
{
    atexit(bar);
    atexit(foo);
    return 0;
}

Notice that foo and bar functions haven’t been called but are registered to get called when the program exits.

These should not return anything nor accept any arguments. You can register up to 32 such functions. They’ll get called in the LIFO order.

Leave a Reply

Your email address will not be published. Required fields are marked *