C exit function
Created By: chatGPT
In C programming, the exit function is used to terminate a program. It is defined in the
stdlib.h
header file. The exit function can be called with an integer value that serves as the program's return status. By convention, a return status of 0 indicates successful termination, while any other value indicates an error or abnormal termination. Below is an example showing how to use the exit function.#include <stdio.h>
#include <stdlib.h>
int main() {
printf("Program is running...\n");
// Terminate the program with a successful exit status
exit(0);
// This line will not be executed due to exit()
printf("This message will never be printed.\n");
}
To use exit effectively, you may also want to include different return codes to indicate various error states. Here's an example where we will terminate the program with an error code if a certain condition is met.
#include <stdio.h>
#include <stdlib.h>
int main() {
int condition = 1; // Simulating a condition that can fail
if (condition) {
printf("An error occurred. Exiting program...\n");
exit(1); // Exit with a status of 1 indicating an error
}
printf("If there were no errors, this would print.\n");
exit(0); // Successful termination
}
Another important aspect of the exit function is that it will also call the atexit functions that have been registered with
atexit()
. This can be useful for performing clean-up actions before the program exits. Here’s how you can register a clean-up function.#include <stdio.h>
#include <stdlib.h>
void cleanup() {
printf("Cleanup tasks are being performed...\n");
}
int main() {
atexit(cleanup); // Register the cleanup function
printf("Running program...\n");
exit(0);
}