Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 987
kamikaze_pilot Avatar asked May 01 '11 23:05

kamikaze_pilot


1 Answers

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

like image 144
Mahesh Avatar answered Oct 13 '22 11:10

Mahesh