Understanding static variables with recursive functions

Apr 19, 2012 at 1:09pm
Hi,

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.

1
2
3
4
5
6
7
8
9
10
void repeatMe()
{
    static int num;
    if(num < 10)
    {
        cout << "Ecooooo" << endl;
        num++;
        repeatMe();
    }
}


This doen't work why? what does the static variable do?
1
2
3
4
5
6
7
8
9
10
11
void repeatMe()
{
    int num;
    if(num < 10)
    {
        cout << "Ecooooo" << endl;
        num++;
        repeatMe();

    }
}


I know I could use a while loop to avoid this issue but I want to understand how static variables work.
Using a while loop.
1
2
3
4
5
6
7
8
9
10
11
void repeatMe()
{
    cout << "Ecooooo" << endl;
    int num;

    while (num < 10)
    {
        num++;
        repeatMe();
    }
}
Thanks a lot.
Last edited on Apr 19, 2012 at 1:10pm
Apr 19, 2012 at 1:16pm
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.
Apr 19, 2012 at 2:01pm
Ok but why it works in the while loop if its in the same location?

I tought that by declaring a variable inside a fuction it would make it global to that function
by defalult, no?


Thanks a lot for your help!
Apr 19, 2012 at 2:14pm
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.

Edit: num, not n
Last edited on Apr 19, 2012 at 2:15pm
Apr 19, 2012 at 2:16pm
I tought that by declaring a variable inside a fuction it would make it global to that function by defalult, no?
No. That's the nature of a static variable.

You know that your variable 'num' is in all cases uninitialized?

Alternatively to the local/static variable 'num' you can pass it as a parameter.
Apr 19, 2012 at 2:39pm
You know that your variable 'num' is in all cases uninitialized?


IIRC static variables are initialized to zero at program start.
Apr 19, 2012 at 2:50pm
Thank you doug4 for the good explanation.


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!
Last edited on Apr 19, 2012 at 2:51pm
Apr 19, 2012 at 2:54pm
> 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.

Try running this program a few times:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
#include <cstdlib>
#include <ctime>

void foo( int a )
{
    if( a == 0 )
    {
        static int one = ( ( std::cout << "initialize foo::one\n" ), 1 ) ;
    }
    else
    {
        static int two = ( ( std::cout << "initialize foo::two\n" ), 0 ) ;
    }
}

void bar( int a )
{
    if( a < 2 )
    {
        static int three = ( ( std::cout << "initialize bar::three\n" ), 3 ) ;
    }
    else
    {
        static int four = ( ( std::cout << "initialize bar::four\n" ), 4 ) ;
    }
}

int main()
{
    std::srand( time(0) ) ;
    int r = std::rand() ;
    if( r%2 ) { foo( r%2 ) ; bar( r%4 ) ; }
    else { bar( r%4 ) ; foo( r%2 ) ; }
}




> IIRC static variables are initialized to zero at program start.

Storage for static variables contains zeroes at program start. The variables are initialized (if required) after the program begins execution.

Apr 19, 2012 at 6:05pm
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.

Thank you all very much for your help!
Topic archived. No new replies allowed.