在 C++ 中递归到 main() 是否合法?
我读到 C++ 标准禁止在 main()
中递归,但是 g++ 毫无怨言地编译了以下代码:
int main()
{
main();
}
任何人都可以澄清这一点吗?
I read that the C++ standard forbids recursion in main()
, but g++ compiles the following code without complaint:
int main()
{
main();
}
Can anyone clarify this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
根据3.6.1/3中的标准,它不是:
使用的定义是:
According to the standard in 3.6.1/3, it's not :
The definition of used being :
我会做鱼并解释为什么这是禁止。在 C 或 C++ 程序开始运行之前,必须首先初始化 CRT。打开 stdin/out/err,调用初始值设定项,诸如此类的事情。有两种基本策略可以完成此任务,一个重要的平台实现细节。
程序的起始地址指向CRT init函数,该函数最终调用main()。在具有精美加载程序的全功能操作系统上很常见,该加载程序可以支持可执行映像中的任意部分。
编译器将代码注入到调用 CRT 初始化函数的 main() 函数中。启动函数始终是 main()。在加载程序功能有限的嵌入式平台上常见。递归 main() 现在是一个问题,CRT 启动代码将被再次调用,并且堆栈状态不可预测。
I'll do the fish and explain why this is verboten. Before a C or C++ program can start running, the CRT has to be initialized first. Open stdin/out/err, call initializers, that sort of thing. There are two basic strategies to get this done, a heavy platform implementation detail.
The program's start address points to the CRT init function, which eventually calls main(). Common on full-featured operating systems that have a fancy loader which can support arbitrary sections in the executable image.
The compiler injects code into the main() function that calls the CRT initialization function. The start function is always main(). Common on embedded platforms with limited loader capabilities. Recursing main() is now a problem, the CRT startup code will be called again with an unpredictable stack state.
此处的主张是,它确实是被明确禁止的:
您当然可以这样做:(
注意我添加了一个 get-out 子句。我什至不能假设无限地编写代码递归,它在我身上重复。)
The claim here is that it is indeed specifically forbidden:
You can, of course, do this:
(Note I added a get-out clause. I can't even hypothetically code infinite recursion, it repeats on me.)
这是不合法的。阅读 3.6.1-3 :
It is not legal. Read 3.6.1-3 :
其他人已经解决了标准部分。但是,我想指出,如果您使用
-pedantic-errors
并至少包含其中一个错误(取决于main
),g++(至少 4.6.2)将拒绝此错误代码>签名):Other people have addressed the standards part. However, I'd like to note that g++ (at least 4.6.2) will reject this if you use
-pedantic-errors
with at least one of these errors (depending onmain
signature):