The main function and exit code
A program is often launched not by a person but by another program, such as a script or a system that checks assignments. The launching program needs to know whether the launched one succeeded, and parsing its output for that is awkward.
Picture a courier back from a delivery. The dispatcher does not need the story of the trip: a mark on the delivery note is enough—delivered or not. A program has the same kind of mark, only it is a number. So main returns a number:
#include <iostream>
int main() {
std::cout << "Done\n"; // Done
return 0;
}Let's go through the body of main line by line:
std::cout << "Done\n";printsDone.return 0;endsmainand hands the number0to whoever launched the program.
The exit code
The int before main is the return type: the function returns an integer. The statement return 0; ends main, and 0 becomes the program's exit code. Whoever launched the program receives it. By convention, 0 means success and any other number means failure.
This is where the delivery-note picture stops working: the mark has no words, only a number, and the program's author decides what each number other than 0 means.
The exit code does not go to the output: return 0; prints nothing. You can see it this way:
- in Visual Studio, when the program ends, the console window shows a line that contains
exited with code 0; - in a Linux or macOS terminal, the command
echo $?shows it.
return takes effect at once: the statements that come after it in main never run.
Ending without return
Of the functions that return a value, only main can do without return. If execution reaches the closing brace of main, the program returns 0, as after return 0;. That is how the Hello, world program works: it has no return, and its exit code is 0. That is why return 0; at the end of main is often left out.
In any other function that returns a value, ending this way is undefined behavior: the C++ standard does not say what happens. The compiler issues a warning in that case.
Common mistake
Here main is declared with void—"no result"—instead of int:
#include <iostream>
void main() { // ✗
std::cout << "Done\n";
}error: 'main' must return 'int'The C++ standard requires main to return int, so clang and GCC do not compile this program.
Key points
mainreturns anint, the program's exit code; by convention0means success.returnends the function at once: the statements after it do not run.- If
mainreaches its closing brace withoutreturn, the program returns0. - In any other function that returns a value, ending without
returnis undefined behavior.
Subscribe to take the course
The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.