关于c ++递归和局部变量的问题 [英] question on c++ recursion and local variables
问题描述
假设我有这个递归:
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变量对于递归树中的那个阶段?
将x和y的范围仅对递归中特定阶段中的函数有效树?
是的。
doSomething(),并且递归树中的子doSomething()重定义x和y,它将重置父类的x和y变量
否。
是在递归树中创建一个全新的x和y变量只有?
是的。
strong>
此示例应该是有帮助的。
#include< iostream>
无效的foo(int temp)
{
int num = temp;
if(temp == 0)
return;
foo(temp-1);
std :: cout<< &#< \t<< num<< \\\
;
}
int main()
{
foo(5);
return 0;
}
输出:
0xbfa4e2d0 1
0xbfa4e300 2
0xbfa4e330 3
0xbfa4e360 4
0xbfa4e390 5
注意 num
的地址不同,它自己的值 num
。
Ideone
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?
will x and y's scope be valid only for the function in that specific stage in the recursion tree?
Yes.
when I call doSomething() again, and the child doSomething() in the recursion tree, redeclares x and y, will it reset the parents' x and y variables as well
No.
is it creating an entirely new x and y variables that is valid for that stage in the recursion tree only?
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:
0xbfa4e2d0 1
0xbfa4e300 2
0xbfa4e330 3
0xbfa4e360 4
0xbfa4e390 5
Notice the address of num
being different and each call has it's own value of num
.
Ideone
这篇关于关于c ++递归和局部变量的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!