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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With