Static variable
|
|
It has been suggested that Static memory allocation be merged into this article. (Discuss) Proposed since January 2013. |
In computer programming, a static variable is a variable that has been allocated statically — whose lifetime or "extent" extends across the entire run of the program. This is in contrast to the more ephemeral automatic variables (local variables are generally automatic), whose storage is allocated and deallocated on the call stack; and in contrast to objects whose storage is dynamically allocated in heap memory.
When a program (executable or library) is loaded into memory, static variables are stored in the data segment of the program's address space (if initialized), or the BSS segment (if uninitialized), and are stored in corresponding sections of object files prior to loading.
The static keyword is used in C and related languages both for static variables and other concepts.
Contents |
Scope [edit]
In terms of scope and extent, static variables have extent the entire run of the program, but may have more limited scope. A basic distinction is between a static global variable, which is in scope throughout the program, and a static local variable, which is only in scope within a function (or other local scope). A static variable may also have module scope or some variant, such as internal linkage in C, which is a form of file scope or module scope.
In object-oriented programming there is also the concept of a static member variable, which is a "class variable" of a statically defined class – a member variable of a given class which is shared across all instances (objects), and is accessible as a member variable of these objects. Note however that a class variable of a dynamically defined class, in languages where classes can be defined at run time, is allocated when the class is defined and is not static.
Example [edit]
An example of static local variable in C:
#include <stdio.h> void func() { static int x = 0; // x is initialized only once across three calls of func() printf("%d\n", x); // outputs the value of x x = x + 1; } int main(int argc, char *argv[]) { func(); // prints 0 func(); // prints 1 func(); // prints 2 return 0; }
See also [edit]
References [edit]
- Kernighan, Brian W.; Ritchie, Dennis M. (1988). The C Programming Language (2nd ed.). Upper Saddle River, NJ: Prentice Hall PTR. ISBN 0-13-110362-8.
- The C++ Programming Language (special edition) by Bjarne Stroustrup (Addison Wesley, 2000; ISBN 0-201-70073-5)