Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
310 views
in Technique[技术] by (71.8m points)

question on c++ recursion and local variables

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 << "" << num << "
" ;
}

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...