c++ - 没有返回类型的 main 的使用在 C++11 中被淘汰了吗?

标签 c++ c++11

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 implicit int 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 implicit int. That means we may get rid of it in another decade or so.

关于c++ - 没有返回类型的 main 的使用在 C++11 中被淘汰了吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37873874/

相关文章:

c++ - 此代码生成段错误。我哪里出错了?

c++ - 使用 C++ 模板类方法的 C 回调

c++ - 是否可以使用 operator new 和 initialiser 语法初始化非 POD 数组?

c++ - 用户定义类型的 std::common_type 特征

c++ - 是否可以编写便于复制初始化的显式构造函数?

C++ stable_partition 编译器错误

python - 如何在 Python 进程中访问由 C++ 进程创建的互斥体?

c++ - 为什么ofstream不能用bind绑定(bind)?

c++ - 从基类继承 std::shared_from_this 时的 std::bad_weak_ptr

C++ 和 OpenMP : How to make the initializer list of a constructor critical?