Static variable
From Wikipedia, the free encyclopedia
In computer programming, static variables typically have a broader scope than other variables. Their values may be set at run-time or may change subtly during program execution.
- See also: Global variable
Contents |
[edit] For constants
Computer programs may store constants in constant variables or in static variables, depending on the available features of the programming language. For example, a program that uses an approximation of pi might be easier to write, read, and maintain with a variable called "PI" instead of multiple occurrences of "3.14159".
[edit] For scope
In the C programming language, static is used with global variables and functions to set their scope to the containing file.
[edit] For local variables
Most programming languages include the feature of subroutines. Variables local to subroutines (local variables) are usually created and destroyed within the subroutine itself. 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 using global variables or external storage, like a file on disk.
[edit] For class variables
Object-oriented programming languages use classes and objects. Static class variables are those that apply to the class instead of the object instances.
[edit] C# Example
public class Request { private static int count; private string url; public Request() { //Create a new instance of Request //Count all requests Request.count++; } public string Url { get { return this.url; } set { this.url = value; } } public static int Count { get { //Do not use the this keyword here //as this refers to "THIS INSTANCE" return Request.count; } //Do not allow the developer to SET this value } }
[edit] C++ Example
class Request { private: static int count; string url; public: void Request() { Request::count++; } string Url() { this->url = value; return this->url; } int Count() const { return Request::count; } };
In this sample count applies to the class, while url applies to each instance