在程序中使用 return

Use of return in a program

在 int main() 块中编写代码块时,为什么我们使用

return 0;

我知道这是因为它告诉 OS 代码 运行 成功了。 但是,即使我使用 return 1、return 38 或类似的东西,如果我的程序仍然成功运行,它对我有何影响。 如果任何数字 x 都可以做同样的事情,数字 0 有什么用?

在许多环境中,从 main() 返回的 return 值可以被任何 运行 您的程序访问。例如,您可以在 bash 中看到这一点,方法是($?bash 特殊变量,其中包含上一个程序中的 return 代码——实际上它多了一点比你做管道时复杂,但为了这个问题的目的,我们会保持简单):

myProgram
if [[ $? -ne 0 ]] ; then
    echo "Something went horribly wrong"
fi

所以这是向 "the outside world" 表明程序成功与否的好方法。

对于我们当中的语言律师,C11 首先在 5.1.2.2.3 Program termination /1(我的重点)中介绍了它:

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.

部分 7.22.4.4 The exit function /5 涵盖了 exit 的行为,因为它与实际完成执行有关:

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.

任何非零值都表示程序异常结束或出现错误。对于独立程序来说,这并不重要,因为这段代码经常被忽略。但是,当在第三方软件、OS、脚本或 shell 中调用时,这可用于错误处理。

参考了类似的问题。 So what does "return 0" actually mean?

还引用了一个 Quora 问题: https://www.quora.com/What-does-return-1-do-in-a-program-in-C