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.


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 )

Facebook photo

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

Connecting to %s