In many environments, the return value passed back from main()
can be accessed by whatever ran your program. For example, you can see this in bash
by doing something like ($?
is the bash
special variable holding the return code from the last program - it's actually a bit more complex than that when you do pipelines but we'll keep it simple for the purposes of this question):
myProgram
if [[ $? -ne 0 ]] ; then
echo "Something went horribly wrong"
fi
So it's a good way to indicate success or otherwise of your program to "the outside world".
For the language lawyer amongst us, it's covered (for C11
) first in 5.1.2.2.3 Program termination /1
(my emphasis):
If the return type of the main
function is a type compatible with int
, a return from the initial call to the main function is equivalent to calling the exit
function with the value returned by the main
function as its argument; reaching the }
that terminates the main
function returns a value of 0.
Section 7.22.4.4 The exit function /5
covers the behaviour of exit
as it pertains to actually finishing execution:
Finally, control is returned to the host environment. If the value of status is zero or EXIT_SUCCESS
, an implementation-defined form of the status successful termination is returned. If the value of status is EXIT_FAILURE
, an implementation-defined form of the status unsuccessful termination is returned. Otherwise the status returned is implementation-defined.