Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can static variables be initialized multiple times?

Tags:

c++

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?

like image 201
dcds Avatar asked Nov 16 '25 22:11

dcds


2 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.

like image 88
john Avatar answered Nov 18 '25 11:11

john


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.

like image 38
463035818_is_not_a_number Avatar answered Nov 18 '25 10:11

463035818_is_not_a_number



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!