In computer programming, a static variable is a variable that has been allocated "statically", meaning that its lifetime (or "extent") is the entire run of the program. This is in contrast to shorter-lived automatic variables, whose storage is stack allocation and deallocated on the call stack; and in contrast to dynamically allocated objects, whose storage is allocated and deallocated in heap memory. Static variables may also be given thread-local storage to ensure that each thread gets an independent instance of the variable.
Variable lifetime is contrasted with scope (where a variable can be used): "global" and "local" refer to scope, not lifetime, but scope often implies lifetime. In many languages, are always static, but in some languages they are Dynamic variable, while are generally automatic, but may be static.
In general, is the allocation of memory at compile time, before the associated program is executed, unlike dynamic memory allocation or automatic memory allocation where memory is allocated as required at run time.
The static keyword is used in C and related languages both for static variables and other concepts. In Rust, an object's Object lifetime can be marked static using the static keyword or with a
This definition is subtly different from a static variable: it only specifies behavior, and hence lifetime, not storage: an own variable can be allocated when a function is first called, for instance, rather than at program load time.
The use of the word static to refer to these variables dates at least to BCPL (1966), and has been popularized by the C language, which was heavily influenced by BCPL. The BCPL definition reads:
Note that BCPL defined a "dynamic data item" for what is now called an automatic variable (local, stack-allocated), not for heap-allocated objects, which is the current use of the term dynamic allocation.
void func() {
static int x = 0;
// x is initialized only once across five calls of func() and the variable
// will get incremented five times after these calls. The final value of x
// will be 5.
x++;
printf("%d\n", x); // outputs the value of x
}
int main() {
func(); // prints 1
func(); // prints 2
func(); // prints 3
func(); // prints 4
func(); // prints 5
return 0;
}
Object constants known at compile-time, such as , are usually allocated statically. In object-oriented programming, the virtual method tables of classes are usually allocated statically. A statically defined value can also be Global variable in its scope ensuring the same Immutable object value is used throughout a run for consistency.
In C++ (since C++11), function-local static initialization (i.e. the initialization of a
In object-oriented programming, static variables are often used to implement the singleton pattern.
private static final Singleton INSTANCE = new Singleton();
private Singleton() {}
public static Singleton instance() {
return INSTANCE;
}
}
|
|