I'm currently practicing with recursive functions and I'm a little confused with static varialbes.
I have this code which is working fine my only confusion is why it stops working if I make the static variable an int? In other words if I delete static it doesnt work.
static is just a global variable with visibility limited to one function. So if you declare it static, there is exactly one variable shared by all the levels of recursion. Without static, the variable is local, which means each function invocation has its own copy of variable's state.
First of all, let's assume that num is initialized to 0 in all cases. Right now it's uninitialized, and should give you some sort of compiler warning, and could screw up these comments if garbage values are used.
In the first case, the first time you enter the function, num is 0. In line 7 it is set to 1. Line 8 calls the function again, and when you enter, num = 1. In line 8, when you call the function again, num = 2.
In the second case, every time you call the function again, num = 0. Because the variable is not static, it is created anew on your function stack every time the function is entered. When you recurse 5 times, there are 5 copies of n on the stack, each initialized to 0 (but modified to n = 1 in line 7).
To see the difference, in your line 6 print statements, dump the value of num also.
You know that your variable 'num' is in all cases uninitialized?
No, I was thinking that "num" in line 3 second example, was ectually holding the value given inside the
if statement but apparently since it is not a static variable it doesn't keep track of any changes made
inside the if statement, right?
I guess my confusion was that we are saying that "num" in line 3 second example, was not a global varialbe to the function but
it is used inside the if statement, that means that it is visible by code inside the if statement which in my eyes it is global to the funtion.
Aparently "num" in line 3 second example, doesnt have visibility to code inside the if statement but code inside the if statement does, is this right?
Thanks a lot and sorry if I dont get the message. You guys are awesome!
> static is just a global variable with visibility limited to one function.
They are different with respect to initialization/deinitialization. Global variables are initialized before main is entered into. A variable with a static storage duration is initialized if and when control reaches its definition for the first time.
Got it, the thing I wasn't understanding is the fact that any local variable declared inside a function is destroyed/reassigned after the function finish its execution and I guess static variables are the exception of the rule.