Question

int main()
{
    return 0;
}

Who receives the value 0 after executing the main function? and what is this value used for after that?

Était-ce utile?

La solution 3

Returning a value from the main() function is equivalent to calling exit() with that value. So your code is similar to:

int main() {
    std::exit(0);
}

The exit status is returned to the runtime library. It can be accessed by the parent process that invoked the program; on Unix this is done using the wait() family of calls. If you run the program from a Unix shell, the exit status is put in the variable $?, or you can test it using control statements like if or while.

Autres conseils

The effect of executing a program is the same as a single call of:

std::exit(main(/* args */))

So the return value of main is the single argument of exit, whatever that means to your system.

Note that the standard only defined two return values, EXIT_SUCCESS and EXIT_FAILURE. Returning zero is equivalent to returning EXIT_SUCCESS. Everything else is implementation defined.

On Unix(like) systems, you can signal exit status to your shell (assumnig bash):

$ ./your-program
$ echo $?
0

In bash, $? is the exit code of the previous command.

The operating system may use this value. In most operating systems, you can query this value after the program has run. How you do this depends on the operating system.

main's return value is passed to process calling your program.

The program calling your program. In the above case it is the OS shell or a batch file/script executing your program.

The return value is passed to std::exit as argument status, which will then do some tidying up and return an exit status to the host environment:

Finally, control is returned to the host environment. If status is zero or EXIT_SUCCESS, an implementation-defined form of the status successful termination is returned. If status is EXIT_FAILURE, an implementation-defined form of the status unsuccessful termination is returned. Otherwise the status returned is implementation-defined.

Consider a program the executes child programs. Many times this would be a shell/terminal/console. When a child exits it can tell it's parent that it has finished and whether it was successful.

consider the program cd which changes directory and rm which removes some files. If you would write a program that cd's to a directory, and subsequently removes all files with rm * then it is really important that the shell/console/terminal is able to tell whether the cd command was successful, because otherwise the contents of a current directory could be removed.

The shell calls e.g. waitpid on the cd command and examines what value is returned. And based on that return value a shellscript programmer can deside to either call rm or do some error handling.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top