The exit()
function in C is used to terminate a program and return a status code to the operating system. It is declared in the stdlib.h
header file. When called, exit()
performs some clean-up operations (like closing open files) before the program terminates.
Syntax:
void exit(int status);
Parameters:
status
: This is an integer value that is returned to the operating system. It typically indicates whether the program ran successfully or encountered an error:- A status of 0 typically signifies successful completion.
- A non-zero status typically indicates an error or abnormal termination.
Behavior:
When exit()
is called:
- Termination of the Program: The program is terminated immediately, and control is passed back to the operating system.
- Clean-up: Before termination, the following actions are performed:
- All buffered output (from
stdout
) is flushed. - Open files are closed.
- Any functions registered with
atexit()
(explained below) are called.
- All buffered output (from
Example Code:
#include <stdio.h>
#include <stdlib.h>
int main() {
printf("Program is starting...\n");
// Some condition that causes abnormal exit
if (1) {
printf("An error occurred. Exiting program...\n");
exit(1); // Exit with status code 1 (indicating error)
}
// This line will not be reached because exit() terminates the program
printf("This will not be printed.\n");
return 0;
}
In the example above:
- The program prints a message, then calls
exit(1)
to terminate the program with a status code of1
(indicating an error). - Any code after the
exit()
call will not be executed, including thereturn 0;
line.
atexit()
and Program Cleanup
You can use the atexit()
function to register functions that should be executed when the program terminates, whether by calling exit()
or by returning from the main()
function. These functions are called in the reverse order in which they were registered.
Example using atexit()
:
#include <stdio.h>
#include <stdlib.h>
void cleanup() {
printf("Cleaning up before exiting.\n");
}
int main() {
// Register cleanup function
atexit(cleanup);
printf("Program is running...\n");
// Exit with status 0 (successful)
exit(0);
}
In this case, cleanup()
will be called when the program exits, ensuring any necessary cleanup steps are performed.
Conclusion:
The exit()
function is a way to terminate a program explicitly, returning a status code to the operating system. It is especially useful when the program encounters errors or needs to exit from deep within a function. It also provides mechanisms to clean up resources before the program finishes, using functions like atexit().