Interview Questions
- What is exit function in C.
- What is atexit function and can we call it more than once in a C program.
What is exit function in C.
The function void exit(int status); terminates calling process normally. Before terminating a process, it performs the following operations:
- Functions registered with atexit are called.
- All streams/files are closed and flushed if buffered, and all files created with tmpfile are removed.
- Control is returned to the calling(host) environment.
Function prototype of exit function
void exit(int status);
#include <stdio.h> #include <stdlib.h> int main(){ printf("Program start\n"); /* Terminating program using exit */ exit(0); printf("It won't get printed ever\n"); return 0; }
Output
Program start
What is atexit function and can we call it more than once in a C program.
The stdlib C Library function int atexit(void (*func)(void)); registers the function pointed to by func to be called when the program terminates. Upon normal termination of the program, function pointed by func is automatically called without arguments. You can register your termination function anywhere in program.
This function returns zero value, if the function was successfully registered, otherwise a non-zero value if unsuccessful.
#include <stdio.h> #include <stdlib.h> void myFunction(){ printf("Program end, Bye Bye\n"); getch(); } int main(){ printf("Program start\n"); atexit(myFunction); return 0; }
Output
Program start Program end, Bye Bye
You can call atexit function more than once, they are all executed in reverse order of their call(the last function to be registered will be the first function to be called).