gpt4 book ai didi

c++ - 自动返回类型扣除是否适用于 main?

转载 作者:太空狗 更新时间:2023-10-29 23:16:23 25 4
gpt4 key购买 nike

我能否在 C++1y (C++14) 中对主函数执行以下操作:

auto main()
{
// ...
}

即使我们不需要使用明确的return 0;,返回类型也会自动为int吗?

最佳答案

不,不允许。 C++14 标准草案 N3690 第 7.1.6.4/10 段规定:

If a function with a declared return type that uses a placeholder type has no return statements, the return type is deduced as though from a return statement with no operand at the closing brace of the function body. [...]

这意味着在 main() 中省略 return 语句会使它的类型 void

段落 3.6.1/5 引入的关于流出 main() 末尾的特殊规则指定:

[...] If control reaches the end of main without encountering a return statement, the effect is that of executing

return 0;

措辞表明程序执行期间的“效果”与出现return 0 相同,而不是return 语句将被添加到程序中(根据引用的段落,这将影响类型推导)。

编辑:

有一个Defect Report为此(courtesy of Johannes Schaub):

Proposed resolution (November, 2013):

Change 3.6.1 [basic.start.main] paragraph 2 as follows:

An implementation shall not predefine the main function. This function shall not be overloaded. It shall have a declared return type of type int, but otherwise its type is implementation-defined. All implementations An implementation shall allow both

  • a function of () returning int and
  • a function of (int, pointer to pointer to char) returning int

as the type...

关于c++ - 自动返回类型扣除是否适用于 main?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24130087/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com