Calling a function On termination of main() in C

Dear readers, A friend of mine taught me this new “trick” where you can call a function when the main() in C exits.

In the Library “stdlib.h” there exists a function

int atexit(void (*func)(void))

the “func” is any function without any arguments.

The atexit() calls the function that you register as soon as the main() terminates.

Here is a simple sample code to demonstrate this.

void func()
printf(“This is after main\n”);
int main()

printf(“in main\n”);
return 0;

The function can be registered anywhere in the main() but it will be called only after the main() terminates.

Hope this helps atleast some of you in doing some cool things. Please feel free to share your ideas.

About vineethkartha

Hi, I am Vineeth Kartha, I hold a Masters degree in Embedded Systems from BITS Pilani, Goa Campus. I currently work as a Software Developer. I am A free software promoter and electronics hobbyist. In my free time I do a little bit of birding and Wildlife photography. I love travelling, reading and blogging.

Posted on July 18, 2015, in Technical and tagged , . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: