Skip to content
Theory · Your First Program · lesson 2 of 7

The main function and exit code

A program is often launched not by a person but by another program. That may be a script or a system that checks assignments. The launching program needs to know whether the run succeeded, and parsing the output for that is awkward. So main returns a number:

C++
#include <iostream>

int main() {
    std::cout << "Done\n";  // Done
    return 0;
}

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.

The exit code does not go to the output: return 0; prints nothing. 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.

Command-line arguments

The C++ standard guarantees two forms of main: int main() and int main(int argc, char* argv[]). The second one receives the words of the command that launched the program—the command-line arguments. argc is the number of words, and argv holds the words themselves; the first one is in argv[0].

C++
#include <iostream>

int main(int argc, char* argv[]) {
    std::cout << argc << ' ' << argv[0] << '\n';  // 1 ./args
}

This program was launched from a terminal with the command ./args. The command has one word—the program's name—so argc is 1. The command ./args red blue gives 3 ./args.

Common mistake

Here main is declared with void—"no result"—instead of int:

C++
#include <iostream>

void main() {  // ✗
    std::cout << "Done\n";
}
TEXT
error: 'main' must return 'int'

The C++ standard requires main to return int, so clang and GCC do not compile this program.