John
John

Reputation: 105

What this static variable function as expected in this recursive senerio?

In my code below variable1 is only being initialized to 0 in the very first call. My concern is that in every recursive call static variable1; is being declared. Will this cause problems with keeps track of the numbers? Or does the compiler know to skip over the declaration in each recursive call?

My code:

void funtion1(numberOfTimesCalled){
    numberOfTimesCalled++;

    static variable1;

    if(numberofTimesCalled = 0){
        variable1 = 0;
    }

    <some processing> 

    variable1= variable1+1;

    if(variable1<10){
        function1(numberOfTimesCalled);
    }
}

Upvotes: 0

Views: 29

Answers (1)

P.P
P.P

Reputation: 121347

My concern is that in every recursive call static variable1; is being declared.

Yes, it's safe as a variable with static storage duration will not be re-declared again. It's lifetime is entire execution of the program and is initialized only once before. So unless you intend to "reset" the value of varaible1, you don't even need the special condition:

  if(numberofTimesCalled == 0){ // assuming you intended to check with ==, 
                                // a single = is for assignment.
        variable1 = 0;
    }

because a variable with static duration will be zero initialized at program startup.

Upvotes: 1

Related Questions