Static variable

This is an old revision of this page, as edited by Furrykef (talk | contribs) at 21:32, 29 October 2005 (style). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

In computer science, there are several precise meanings of static variable, depending upon the use and context. In all cases, however, the word static refers to the requirement that the variable remains unchanged and sometimes even unavailable outside the realm of definition.

Static variables as constants

Often, programmers make use of constants, which are defined symbols in place of numbers. For example, a program which performs calculations using an approximation of pi might be easier to write, read and maintain with a variable called "PI" instead of retyping "3.14159" throughout the program. Many programming languages provide a facility for such constants, negating the need for static variables in this context.

In other cases a constant may be defined at run-time, or change subtly during the course of program execution. Examples might include programs which accept a user input during startup, or redirect operations or calculations based on different user-defined modes.

Static variables as local function variables

Most programming languages include the concept of functions (also known as methods or procedures). These structures resemble smaller programs that can be called as subtasks from the main application, or even from other subtasks. Functions simply perform their intended operation and return control to the caller. Usually, any variables local to the function (or function variables) are created and destroyed within the function itself.

Some languages allow functions to retain the value of variables between calls, so that the function can preserve its state if necessary. For example, with a static variable a function could record the number of times it has been executed using an internal counter. This would only otherwise be possible using global variables or an external storage method, like a file on disk.

Static variables as class variables

Object-oriented programming languages contain the concept of classes, which allow data and functions to be grouped together, and objects where a class is instantiated. Static variables in this context are those which apply to the class, not each object instance.