The return 0; statement
What you'll learn: How your program tells the operating system that it finished its job successfully.
The Handshake at the Finish Line
Imagine you hire a courier to deliver a package. When the job is done, you expect a quick status report. If the courier says, "Code 0," you know everything went perfectly. If they say, "Code 1," you know there was a flat tire. In C programming, the return 0; statement is that final status report.
Because the main function is the starting point of your program, it eventually needs to reach an ending point. When your code hits return 0;, it effectively taps the operating system on the shoulder and says, "I’m done, and everything went exactly as planned."
How it looks in code
In C, the main function is usually defined with int at the beginning, which stands for "integer." This is a promise that the program will hand back a whole number when it finishes.
#include <stdio.h>
int main() {
printf("Hello, World!");
// The program finishes here
return 0;
}
Why the number zero?
You might wonder why we don’t return 1 or 100. In the world of operating systems (like Windows, macOS, or Linux), there is a long-standing convention:
- 0 means "Success." No news is good news!
- Any other number (like 1, 2, or -1) usually indicates that an error occurred.
Think of it like a green light. By returning 0, you are giving the "green light" to any other program that might be waiting for yours to finish. If you were writing a complex system where one program triggers another, that second program would check this return value to decide whether to continue or stop and sound an alarm.
A clean exit
Even though many modern compilers will automatically assume you meant to return zero if you forget to type it, writing it explicitly is considered good "grammar." It acts as a clear signpost for anyone reading your code that says: "This is the intentional end of the journey."
Key takeaway
The return 0; statement gracefully exits the program and signals to the computer that the code ran successfully without errors.