gpt4 book ai didi

c++ - 对主 C++ 的递归调用

转载 作者:可可西里 更新时间:2023-11-01 18:14:59 25 4
gpt4 key购买 nike

<分区>

Possible Duplicate:
Can main function call itself in C++?

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

我编写了如下程序,但我在 10 次后停止了递归,就好像我要让它继续运行一样,它会在 41000 左右的值处停止。

我的问题:在 C++ 中递归调用 main 函数如何合法,是否应该执行此程序以堆栈溢出或内存错误等?请解释。

#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

谢谢

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