- Static variable
In
computer programming , static variables data value persists for the life of the running process and typically have a broader scope than other variables. Their values may be set atrun-time or may change subtly during program execution. The terminology is C and C++ based, but also used in many derived programming languages, in languages with different heritage the same concept may instead be called global variables.For constants
Computer program s may store constants in constant variables or in static variables, depending on the available features of theprogramming language . For example, a program that uses an approximation ofpi might be easier to write, read, and maintain with a variable called "PI" instead of multiple occurrences of "3.14159"For scope
In the C programming language, "static" is used with global variables and functions to set their scope to the containing file. In local variables, "static" is used to store the variable in the statically allocated memory instead of the automatically allocated memory. While the language does not dictate the implementation of either type of memory, statically allocated memory is typically reserved in data segment of the program at compile time, while the automatically allocated memory is normally implemented as a transient call stack.
For local variables
Most programming languages include the feature of
subroutine s. Variables local to subroutines (local variable s) are usually created and destroyed within the subroutine itself (so-calledautomatic variable s). Some languages, however, (e.g., the C programming language) allow subroutines to "retain" the value of variables between calls, so that the function can preserve its state if necessary. For example, a static variable can record the number of times its subroutine has been executed. Doing so is otherwise possible usingglobal variables or external storage, like a file on disk.For class variables
Object-oriented programming languages use classes and objects. In this case, a class variable means a variable that is not associated with instances of the class. There is exactly one copy of the variable that is shared among methods of all instances no matter how many or how few instances exist. In C++, class variables are known as static data members.C# Example
C++ Example
In this sample, count applies to the class while url applies to each instance. Note that the count variable must be initialized outside the class.
References
http://ee.hawaii.edu/~tep/EE160/Book/chap14/subsection2.1.1.6.html
See also
*
Variable
*Thread-local storage
*External variable
Wikimedia Foundation. 2010.