当我运行这段代码时,输出是:
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/