This article is missing information about the use of the static keyword to declare class methods in C++ and Java.(April 2014)
In some programming languages such as C (and its close descendants like C++, Objective-C, and Java),
static is a reserved word controlling both lifetime (as a static variable) and visibility (depending on linkage). The effect of the keyword varies depending on the details of the specific programming language.
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 (not to be confused with classes in object-oriented programming), as can
register (which are also reserved words). 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:
externfor all top-level declarations in a source file,
autofor variables declared in function bodies.
||program execution||external (whole program)|
||program execution||internal (translation unit only)|
In these languages, the term "static variable" has two meanings which are easy to confuse:
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.
A variable declared as
static at the top level of a source file (outside any function definitions) is only visible throughout that file ("file scope", also known as "internal linkage"). In this usage, the keyword
static is known as an "access specifier".
Similarly, a static function – a function declared as
static at the top level of a source file (outside any class definitions) – is only visible throughout that file ("file scope", also known as "internal linkage").
Variables declared as
static inside a function are statically allocated, thus keep their memory location throughout all program execution, while having the same scope of visibility as automatic local variables (
register), meaning they 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.
Similarly, a static method – a method declared as
static inside a class definition – is meant to be relevant to all instances of a class rather than any specific instance. A method declared as
static can be called without instantiating the class.
This section needs expansion. You can help by adding to it. (April 2020)
Edited: 2021-06-18 15:14:43