Return of main function

Asked

Viewed 165 times

6

Studying C/C++ I learned that we put the return 0 at the end of the function main() to indicate that the program worked correctly if this occurs. But if this does not occur, a value other than 0 will be returned by main(). What does this value indicate specifically? I believe it is not a random number.

2 answers

7


Just as it is possible to pass arguments to the code by the function main() through the parameter argv (with the help of argc) And this data comes from whoever called the executable, you can also return a data to who called it. Usually who called is the operating system (by action of some user or script that takes care of it) and it is he who will receive this information to be used in some way, for example a script can take this and decide what to do.

The number that will return is defined by yourself for your application and should document this well so that whoever is calling it can use this result for something according to the semantics that you wanted to give and that makes some sense. In general each number indicates some specific error it gave, according to its documentation.

But it is a mistake that you need to use the return 0, if you don’t do this there will be an implicit return of 0, at least this is true for all the best known compilers.

And there is another detail, almost every time you return an error you will do it through, directly or indirectly, the function exit() or something similar, since this will occur in another part of the code than the main() and shall close immediately.

  • IS standard in C11/C18 need not return value in main?

  • Yeah, as far as I’ve known since C99.

  • I found in 5.1.2.2.3 of the draft "reaching the } that Terminates the main Function Returns a value of 0."

5

The number returned only makes sense in the context of the program you created. If you are aware of a possible error, you can put return 1 at one point, and return 2 in another. If the program eventually fails, it becomes easier to trace what was the reason for the error by the returned code.

  • 1

    But out of context, there is some meaning to it?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.