问题描述
假设我有这个递归:
void doSomething(double j)
{
double x ;
double y;
x = j -1;
y = j -2;
doSomething(x + y);
x = j + 31;
y = j + 12;
}
我知道这个递归执行无限,
我的问题是关于在递归树中的变量x和y的范围...将x和y的范围仅对递归树中特定阶段的函数有效吗?或者当我再次调用doSomething()时,当递归树中的子doSomething()重命名x和y时,它将重置父类的x和y变量,还是创建一个全新的x和y变量对于递归树中的那个阶段?
是的。
否。
是的。
strong>
此示例应该是有帮助的。
#include< iostream>
void foo(int temp)
{
int num = temp;
if(temp == 0)
return;
foo(temp-1);
std :: cout<< &#< \t<< num<< \\\
;
}
int main()
{
foo(5);
return 0;
}
输出:
注意 num
的地址不同,它自己的值 num
。
suppose I have this recursion:
void doSomething(double j)
{
double x;
double y;
x = j -1;
y = j -2 ;
doSomething(x+y);
x = j + 31;
y = j + 12 ;
}
I know that this recursion executes infinitely, but just ignore that
My question is with regards to variables x and y's scope in the recursion tree...will x and y's scope be valid only for the function in that specific stage in the recursion tree? or when I call doSomething() again, when the child doSomething() in the recursion tree redeclares x and y, will it reset the parents' x and y variables as well or is it creating an entirely new x and y variables that is valid for that stage in the recursion tree only?
Yes.
No.
Yes.
Edit 1:This example should be helpful.
#include <iostream>
void foo( int temp )
{
int num = temp;
if( temp == 0)
return;
foo(temp-1) ;
std::cout << &num << "\t" << num << "\n" ;
}
int main()
{
foo(5) ;
return 0;
}
Output:
Notice the address of num
being different and each call has it's own value of num
.Ideone
这篇关于关于c ++递归和局部变量的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!