为什么计数器递增?

Joh*_*nor 2 c++ recursion

当我运行此代码时输出为:

hello5
hello4
hello3
hello2
hello1
0
1
2
3
4
Run Code Online (Sandbox Code Playgroud)

我明白了,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;
}
Run Code Online (Sandbox Code Playgroud)

Luc*_*ore 6

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

   cout<<"hello"<<counter<<endl;
   myFunction(--counter);
   cout<<counter<<endl; // <--- here
Run Code Online (Sandbox Code Playgroud)

由于参数是按值传递的,因此在递归调用中不会修改局部变量.即你传递的副本--counter.所以在通话结束后,无论counter内部如何修改,你都会得到前计数器.