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;
}
Run Code Online (Sandbox Code Playgroud)
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?
joh*_*ohn 10
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.