In the main function of a C++ program, what does `return 0` do and mean? [duplicate]

This defines the exit status of the process. Despite being an int, on Unix-like systems, the value is always in the range 0-255 (see Exit and Exit Status). On Microsoft systems you may use 32-bit signed integers as exit codes, which you can check with %ERRORLEVEL%. For portability, I’d recommend sticking to the 0-255 range.

Here is a trivial example:

$ cat -n exit_code.cpp 
     1  int main()
     2  {
     3      return 42;
     4  }
     5  

Build:

$ make exit_code
g++ exit_code.cpp -o exit_code

Run (in bash):

$ ./exit_code

Check the exit status:

$ echo $?
42

Conventionally, a status of zero signifies success and non-zero failure. This can be useful in shell scripts, and so forth to indicate the level of failure, if any:

$ ./exit_code
exit_status=$?
if [[ ${exit_status} ]] ; then
    echo "The process failed with status ${exit_status}."
else
    echo "Success!"
fi
The process failed with status 42.

Following the comments below…

In the standard C++ header <cstdlib>, the following macros are defined:

#define EXIT_SUCCESS 0
#define EXIT_FAILURE 1

However, the Exit Status section of the GNU C Library documentation, describing the same macros, sagely states:

Portability note: Some non-POSIX systems use different conventions for exit status values. For greater portability, you can use the macros EXIT_SUCCESS and EXIT_FAILURE for the conventional status value for success and failure, respectively. They are declared in the file stdlib.h.

Leave a Comment