Stephen Prata 在他的书 C++ Primer Plus [p 31] 中说:
Many existing programs use the classic C function header instead:
main() // original C style
Under classic C, omitting the return type is the same as saying that the function is type int. However, C++ has phased out that usage.
但是 C++11 草案 3.6.1->2 说
An implementation shall not predefine the main function. This function shall not be overloaded. It shall have a return type of type int, but otherwise its type is implementation-defined.
测试结果
$ g++ -Werror=pedantic MainCheck.cpp -o MainCheck
MainCheck.cpp:3:6: error: ISO C++ forbids declaration of ‘main’ with no type [-Werror=pedantic]
main()
$ # also means g++ don't conform to the standard
证实 Prata 先生所说的 C++ 标准是正确的。
C++11 草案中是否有条款不鼓励使用 :
main() // that is without return type.
是
It shall have a return type of type int
本身就是这样的条款?
最佳答案
另见 What should main()
return in C and C++?
ISO/IEC 14882:1998 包含:
§7 Declarations
¶7 Only in function declarations for constructors, destructors, and type conversions can the decl-specifier-seq be omitted.78)
和脚注 78 说:
The “implicit int” rule of C is no longer supported.
C++11 标准中的¶9 和脚注 89 中有相同的语句。
因此,没有返回类型声明的 main()
从来都不是标准 C++ 的一部分,但直到 C++98 标准被创建之前(并且可能更长一点向后兼容的原因)。
如果您查看 Stroustrup 的“C++ 设计与演化”(1994 年出版),§2.8 C 声明语法 说:
Allowing the type specifier to be omitted (meaning
int
by default) also led to complications. … The negative reaction to changes in this area from users was very strong. … I backed out the change. I don't think I had a choice. Allowing that implicitint
is the source of many of the annoying problems with the C++ grammar today. … Finally, ten years later, the C++ ANSI/ISO standard committee has decided to deprecate implicitint
. That means we may get rid of it in another decade or so.
关于c++ - 没有返回类型的 main 的使用在 C++11 中被淘汰了吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37873874/