< C++ Programming < Programming Languages < C++ < Code < Keywords < static
Permanent storage

Using the static modifier makes a variable have static lifetime and on global variables makes them require internal linkage (variables will not be accessible from code of the same project that resides in other files).

static lifetime
Means that a static variable will need to be initialized in the file scope and at run time, will exist and maintain changes across until the program's process is closed, the particular order of destruction of static variables is undefined.

static variables instances share the same memory location. This means that they keep their value between function calls. For example, in the following code, a static variable inside a function is used to keep track of how many times that function has been called:

void foo() {
  static int counter = 0;
  cout << "foo has been called " << ++counter << " times\n";
}

int main() {
  for( int i = 0; i < 10; ++i ) foo();
}

This article is issued from Wikibooks. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.