I was wondering how static worked. Here is an example:
void count()
{
static int x = 1;
cout << "Static: " << x << endl;
x++;
return;
}
int main()
{
//Static variable test
cout << endl;
count();
count();
}
This program gives an output of “1 and 2”. But I was wondering when the function “count” is called for the second time, why isn’t the “static int x = 1” line executed?
This is a language rule; the initialization of a
staticvariable is only performed once.Note that this is different from
which would reset
xto 1 in every call.