Static (keyword)


In some programming languages such as C, static is a reserved word controlling both lifetime and visibility. The effect of the keyword varies depending on the details of the specific programming language.

Common C/C++ behavior

In C and C++, the effect of the static keyword in C depends on where the declaration occurs.
static may act as a storage class, as are extern, auto and register. Every variable and function has one of these storage classes; if a declaration does not specify the storage class, a context-dependent default is used:
Storage classLifetimeVisibility
externprogram executionexternal
staticprogram executioninternal
auto, registerfunction execution

In these languages, the term "static variable" has two meanings which are easy to confuse:
  1. A variable with the same lifetime as the program, as described above ; or
  2. A variable declared with storage class static.
Variables with storage class extern, which include variables declared at top level without an explicit storage class, are static in the first meaning but not the second.

Static global variable

A variable declared as static at the top level of a source file is only visible throughout that file. In this usage, the keyword static is known as an "access specifier".

Static function

Similarly, a static functiona function declared as static at the top level of a source file is only visible throughout that file.
This usage is deprecated in C++ and an unnamed namespace should be used instead to achieve the same result.

Static local variables

Variables declared as static inside a function are statically allocated, thus keep their memory cell throughout all program execution, while having the same scope of visibility as automatic local variables, meaning remain local to the function. Hence whatever values the function puts into its static local variables during one call will still be present when the function is called again.

C++ specific

Static member variables

In C++, member variables declared as static inside class definitions are class variables.

Static method

Similarly, a static methoda method declared as static inside a class definitionis meant to be relevant to all instances of a class rather than any specific instance. A method declared as static can be called without intanstiating the class.

Java