Can static variables be initialized multiple times?

Viewed 4340

I have read that static variables in c/c++ only initialised once.

But when i tried to experiment with it. I found that they can be initialised multiple times

#include <iostream> 
#include <string> 
using namespace std; 

void demo(int value) 
{ 
    // static variable 
    static int count = 0; 
    count = value; 
    cout << count << " "; 



} 

int main() 
{ 
    for (int i=0; i<5; i++)  
        demo(i+1); 
    return 0; 
} 

In above code my initialised static variable count multiple times.

output is above code is : 1 2 3 4

is I am missing anything here?

3 Answers

count = value; is not initialization, it's assignment. Static variables can be assigned as many times as you wish.

static int count = 0; is initialization and that happens only once, no matter how many times you call demo.

Any variable can be initialized only once. Static is no different with respect to that. What is special about static local variables is that their value persists between function calls. And this of course only makes sense if the line that initialized it is only executed on the first function call. Consider this example:

#include <iostream> 
#include <string> 
using namespace std; 

void demo() 
{ 
    // static variable 
    static int count = 0; 
    std::cout << ++count << " ";
} 

int main() 
{ 
    for (int i=0; i<5; i++) demo(); 
    return 0; 
} 

It prints

1 2 3 4 5 

because the static in static int count = 0; means: only on the very first invocation of the function count is initialized with 0.

When a variable is declared as static, space for it gets allocated for the lifetime of the program.

Even if the function is called multiple times, space for the static variable is allocated only once and the value of variable in the previous call gets carried through the next function call.

count = value;-> This is assignment,and in this case static variables has same behavior like other data type (int for example).

Related