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, 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:

C++
#include <iostream>

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

Let's go through the body of main line by line:

  1. std::cout << "Done\n"; prints Done.
  2. return 0; ends main and hands the number 0 to 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:

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.

Key points

  • main returns an int, the program's exit code; by convention 0 means success.
  • return ends the function at once: the statements after it do not run.
  • If main reaches its closing brace without return, the program returns 0.
  • In any other function that returns a value, ending without return is undefined behavior.

Subscribe to take the course

The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.

Sign in another way