Exiting the program with exit()
What you'll learn: How to immediately stop your program from anywhere in your code using the exit() function.
The emergency exit
In most C programs you have written so far, the program ends when the main() function reaches its final closing brace. Think of this like a train reaching the final station at the end of the line. Everything stops because there is nowhere left to go.
However, sometimes you need to jump off the train early. Imagine a program that asks for a password; if the user fails ten times, you don't want the program to keep running other functions—you want it to shut down immediately. This is where the exit() function comes in. Unlike a return statement, which only takes you out of the current function, exit() shuts down the entire program instantly, no matter how many nested functions deep you are.
How to use exit()
To use this tool, you must include the <stdlib.h> header at the top of your file. The function requires one integer argument, known as a "status code." By convention, passing 0 tells the operating system that the program finished successfully. Passing any non-zero number (usually 1) signals that the program closed because of an error.
#include <stdio.h>
#include <stdlib.h> // Required for exit()
void check_system_health(int temperature) {
if (temperature > 100) {
printf("Critical Overheat! Shutting down system...\n");
exit(1); // Immediate stop with error status
}
}
int main() {
printf("Starting engine...\n");
check_system_health(150); // This will trigger the exit
printf("This line will never be printed.");
return 0;
}
Why not just use return?
If you are inside main(), return 0; and exit(0); do the exact same thing. But if you are inside a function called check_system_health() (which is called by main()), a return would only take you back to main(). The program would continue to run the next line of code. exit() is the "nuclear option"—it doesn't go back to the caller; it closes the doors and turns out the lights for the entire process.
Key takeaway
Use exit(0) for a clean, immediate shutdown and exit(1) to stop the program when a fatal error occurs.