为什么 main 的默认返回值为 0 而不是 EXIT_SUCCESS?

2022-01-19 00:00:00 return main standards c++

ISO 1998 c++ 标准规定在 main 中不显式使用 return 语句等同于使用 return 0.但是如果一个实现有不同的标准无错误"代码,例如 -1?

The ISO 1998 c++ standard specifies that not explicitly using a return statement in the main is equivalent to use return 0. But what if an implementation has a different standard "no error" code, for example -1?

为什么不使用标准宏 EXIT_SUCCESS 将被 0-1 或任何其他值替换,具体取决于实现?

Why not use the standard macro EXIT_SUCCESS that would be replaced either by 0 or -1 or any other value depending on the implementation?

C++ 似乎强加了程序的语义,这不是只应描述程序行为方式的语言的角色.此外,错误"返回值的情况有所不同:只有 EXIT_FAILURE 是标准的错误"终止标志,没有明确的值,例如1".

C++ seems to force the semantic of the program, which is not the role of a language which should only describe how the program behaves. Moreover the situation is different for the "error" return value: only EXIT_FAILURE is a standard "error" termination flag, with no explicit value, like "1" for example.

这些选择的原因是什么?

What are the reasons of these choices?

推荐答案

main() 返回零与您所要求的基本相同.从 main() 返回零不必将零返回到主机环境.

Returning zero from main() does essentially the same as what you're asking. Returning zero from main() does not have to return zero to the host environment.

来自 C90/C99/C++98 标准文档:

From the C90/C99/C++98 standard document:

如果status的值为0或EXIT_SUCCESS,则返回成功终止的实现定义形式.

If the value of status is zero or EXIT_SUCCESS, an implementation-defined form of the status successful termination is returned.

相关文章