gpt4 book ai didi

c++ - 递归中的主要功能

转载 作者:行者123 更新时间:2023-12-03 07:11:55 25 4
gpt4 key购买 nike

我尝试了main函数中的递归,但是为什么'i'变量没有得到更新,它直到i = 1才更新,然后保持不变。
下面是代码:

int main(int i = 0)
{
std::cout << "i value" << i << std::endl;
if (i == 3)
return 0;
std::cout << "hello" << std::endl;
main(i++);
}

最佳答案

参见例如cppreference/main_function:

The main function has several special properties:

  1. It cannot be used anywhere in the program

    a) in particular, it cannot be called recursively

    b) its address cannot be taken

[...]


您不能递归调用 main。另外,您的签名不正确。正确的签名是:
int main () { body }                                                (1)     
int main (int argc, char *argv[]) { body } (2)
/* another implementation-defined form, with int as return type */ (3)
对于(3),您需要检查您的实现,但我不知道一个允许 int main(int)的实现(尽管我没有打扰过检查)。
最后但并非最不重要的一点, foo(i++);将递增 i,然后使用 foo的原始值调用 i。您可能需要 foo(++i);或更确切地说 foo(i + 1);
TL; DR
int my_main(int i=0) {
// put code here
my_main(i + 1);
}

int main() {
my_main();
}

关于c++ - 递归中的主要功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64740256/

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