主C ++上的递归调用 [英] Recursive call on main C++

查看:58
本文介绍了主C ++上的递归调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
主函数可以用C ++调用自身吗?

我发现这个问题非常有趣,但有点虚幻.问题6.42 C ++如何通过Dietel进行编程可以在系统上递归调用main吗?编写一个包含main函数的程序.包括静态局部变量count并初始化为1.每次调用main时,递增并打印count的值..编译您的程序.会发生什么?

I found this problem very interesting but illusive a bit. Question 6.42 C++ how to program by Dietel "Can main be called recursively on your system? write a program containing a function main. Include Static local variable count and initialize to 1. Post-increment and print the value of count each time main is called. Compile your program. What happens ?

我写了下面的程序,但是我让递归停止了10次,好像要保持它运行一样,它将停止在41000左右.

I wrote the program as below but instead I made the recursion stops after 10 times as if I were to keep it running it will stops at a value around 41000.

我的问题:用c ++递归调用main函数合法,应该执行此程序以在堆栈上溢出或出现内存故障等.请解释.

my question: how is it legal to call recursively main function in c++, should this program be executed to stack over flow or memory fault, etc.. ? Please explain.

#include <iostream>
using namespace std;
int main()
{
       static int count = 0;
       count++;
       if(count <= 10) {
                cout << count << endl;
                return main(); //call main
                }//end if

       system("pause");
       return 0;//successful completion
}//end main

谢谢

推荐答案

在C ++中递归调用 main()函数合法吗

这是不合法的.C ++语言标准声明函数主程序不得在程序内使用"(C ++ 11§3.6.1/3).调用该函数是一种使用"形式.

It is not legal. The C++ language standard states that "The function main shall not be used within a program" (C++11 §3.6.1/3). Calling the function is a form of "use."

任何调用 main()的程序都表现出不确定的行为(从技术上讲,这样的程序格式错误,因为违反的规则是可诊断的语义规则,但是如果大多数编译器使我感到惊讶,拒绝了该程序).请注意,这不会阻止启动程序的运行时基础结构调用 main()函数.

Any program that calls main() exhibits undefined behavior (technically, such a program is ill-formed because the rule being violated is a diagnosable semantic rule, though I'd be surprised if most compilers rejected the program). Note that this does not prevent the runtime infrastructure that starts your program from calling the main() function.

这篇关于主C ++上的递归调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆