Details of static local variable instances in C++

  • 2020-05-17 05:59:03
  • OfStack

Details of static local variable instances in C++

I used to use and understand static before global variables, so much so that static was even used as a pronoun of global variables, but static can also act before local variables

Significance of static local variables:

1. Allocate space on the global data stack
2. Scope is limited to the current function (local)
3. The life cycle is the entire program and does not end with the end of the current function
4. The assignment takes effect at the first initialization, and the subsequent initialization assignment is automatically skipped

Such as


void fn()
{
  static n=10;
  cout<<n<<endl;
  n++;
}

Here n is a static local variable, only the first fn function will be called static n=10, and will not be called again

There are examples of singletons implemented using this one-declare assignment feature

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: