user8453703
user8453703

Reputation:

Use of return in a program

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

Answers (2)

shockawave123
shockawave123

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

paxdiablo
paxdiablo

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 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.

Upvotes: 2

Related Questions