这个问题是出于好奇;在为测试程序编写 main 时,我没有从 main
返回任何内容(main
中没有 return
语句)。但我将 main 声明为 int main()
。并且编译成功。
好像有任何其他函数用 int
返回类型编写但实际上没有返回 int
,我会得到一个错误
'Function name' must return value
那么为什么编译器不会对 main
函数报错呢?
最佳答案
通常不允许控制流到达非 void 函数的末尾而不返回任何内容。按照标准中的规定,main
函数的处理方式不同。
来自 http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2009/n2960.pdf :
§ 3.6.1/5
If control reaches the end of main without encountering a return statement, the effect is that of executing return 0;
至于理由,老实说,我不确定。如果有人知道,请将其添加到我的答案中或作为评论。
关于c++ - 为什么主函数没有返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19293642/