关于c ++递归和局部变量的问题 [英] question on c++ recursion and local variables

查看:152
本文介绍了关于c ++递归和局部变量的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这个递归:

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆