The Return Value of main( )

This lesson explains the return value of main() and how we can specify the return value.

We have seen that main() is a function. Program execution starts with main() and branches off to other functions from there. The definition of main() that we have used so far has been the following:

void main() {
    // ...
}

According to that definition main() does not take any parameters and does not return a value. In reality, in most systems, every program necessarily returns a value to its environment when it ends, which is called an exit status or return code. Because of this, although it is possible to specify the return type of main() as void, it will actually return a value to the operating system or launch environment.

The return value of main() #

Programs are always started by an entity in a particular environment. The entity that starts the program may be the shell where the user types the name of the program and presses the enter key, a development environment where the programmer clicks the [Run] button and so on.
In D and several other programming languages, the program communicates its exit status to its environment by the return value of main().

The exact meaning of return codes depends on the application and the system. In almost all systems a return value of zero means a successful completion, while other values generally mean some type of failure. There are exceptions to this, though. For instance, in OpenVMS, even values indicate failure while odd values indicate success. Still, in most systems, the values in the range [0, 125] can be used safely as return codes, with values 1 to 125 having a meaning specific to that program.
For example, the common Unix program ls, which is used for listing contents of directories, returns 0 for success, 1 for minor errors and 2 for serious ones.

In many environments, the return value of the program that has been executed most recently in the terminal can be seen through the $? environment variable. For example, when we ask ls to list a file that does not exist, its nonzero return value can be observed with $? as seen below.

Note: In the command line interactions below, the lines that start with # indicate the lines that the user types. If you want to try the same commands, you must enter the contents of those lines except for the # character. Also, the commands later in the lesson start a program named deneme; replace that name with the name of your test program.
Additionally, although the following examples show interactions in a Linux terminal, they would be similar but not exactly the same in terminals of other operating systems.

# ls a_file_that_does_not_exist
ls: cannot access a_file_that_does_not_exist: No such file or directory 
# echo $?
2     ← the return value of ls

Get hands-on with 1400+ tech skills courses.