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?
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.
yes, x and y are stack variables, and thus are independent between each call. A fresh, stack-based x and y will be created for each call to
doSomething
.If you wanted them to be the same variable in each call, you should declare them
static
Every time a function is invoked, there are new local variables
x
andy
created, that are unrelated to any other invocation of the function. This is what makes local variables different from global variables.You are passing x + y by value into the function doSomething(). This means that on the function stack doSomething() will have access to one local variable j with its value set from the function below it on the stack to whatever x + y evaluates to (i.e the function that called them). Since this variable is completely separate from that in the parent function, modifying its value will have no affect on variables below it on the stack.
If, however, you want j to be the exact same variable as in the parent function then you can do something like:
Notice the & after the double, this tells the compiler that the function accepts the value of a double by its address, which is called appropriately enough passing by address. Here in the child of every doSomething() j is an alias for the variable willChange in the function below it on the stack.
If you want to modify x and y specifically then maybe do something like
Yes.
No.
Yes.
Edit 1: This example should be helpful.
Output:
Notice the address of
num
being different and each call has it's own value ofnum
. Ideone