Alex Rivera | Logout

question on c++ recursion and local variables

Asked 2011-05-01T23:43:08.647
12

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?

Edit
Report

1 Answer

5

Every call gets its own copy of the variables. Assigning to the copy in one function call has no effect on the versions in any other function call. That's why the recursion has to communicate between "stages" by passing arguments and returning a value.

answered 2011-05-01T23:44:10.063

Your Answer