Reputation:
While writing a block of code in int main() block,why do we use
return 0;
I know it's because it tells the OS that the code ran successfully. But even if I use things like return 1, return 38 or similar things how does it effect me if my program still runs successfully. What's the use of the numeric 0 then if any number number x can do the same?
Upvotes: 0
Views: 72
Reputation: 697
Any value different from zero is a sign that program ended abnormally or with an error. For stand-alone programs it doesn't really matter all that much, as this code is often ignored. However, for when called within a third party software, the OS, a script, or a shell, this could be used for error handling.
Reference to a similar question. So what does "return 0" actually mean?
Also a reference to a Quora Question: https://www.quora.com/What-does-return-1-do-in-a-program-in-C
Upvotes: 1
Reputation: 881573
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 withint
, a return from the initial call to the main function is equivalent to calling theexit
function with the value returned by themain
function as its argument; reaching the}
that terminates themain
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 isEXIT_FAILURE
, an implementation-defined form of the status unsuccessful termination is returned. Otherwise the status returned is implementation-defined.
Upvotes: 2