c++ - 为什么计数器递增?

标签 c++ recursion

当我运行这段代码时,输​​出是:

hello5
hello4
hello3
hello2
hello1
0
1
2
3
4

直到hello1我才明白,但我不知道为什么它会递增。谁能给我解释一下?

#include <iostream>
#include <iomanip>
using namespace std;

void myFunction( int counter)
{
    if(counter == 0)
        return;
    else
    {
        cout << "hello" << counter << endl;
        myFunction(--counter);
        cout << counter << endl;
        return;
    }
}

int main()
{
    myFunction(5);

    return 0;
}

最佳答案

它不是递增的,你只是在递归调用后打印值:

   cout<<"hello"<<counter<<endl;
   myFunction(--counter);
   cout<<counter<<endl; // <--- here

由于参数是按值传递的,因此在递归调用内部不会修改局部变量。 IE。您正在传递 --counter 的拷贝。所以在调用之后,不管里面的counter怎么修改,你都会得到ex counter。

关于c++ - 为什么计数器递增?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10008860/

相关文章:

c++ - 编写多个 If 语句的优雅方式

c++ - 专门的纯虚拟模板函数的另一个问题(未定义的引用)

c++ - 为什么 C++ 函数调用便宜?

PHP递归数组使用MYSQL数据

c++ - 在 C++ 中使用 OpenMP 并行化递归函数

regex - Perl 中的递归正则表达式

c++ - 如何正确添加状态栏?

c++ - 是否可以在 QGridLayout 中设置小部件之间的最小空间?

Python 3 Count 在函数内更新,但值在函数外不更新

php - 这是 PHP 递归的废话吗?