Static variable: Difference between revisions

Content deleted Content added
m style
Line 1:
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 Variablesvariables as Constantsconstants==
 
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 language|programming languages]] provide a facility for such constants, negating the need for static variables in this context.
Line 7:
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 Variablesvariables as Locallocal Functionfunction Variablesvariables==
 
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 [[Local_variable|variables local to the function]] (or [[function variables]]) are created and destroyed within the function itself.
Line 13:
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 Variablesvariables as Classclass Variablesvariables==
 
[[Object-oriented programming|Object-oriented programming languages]] contain the concept of [[Class (computer science)|class]]es, which allow data and functions to be grouped together, and [[Object (computer science)|object]]s where a class is instantiated. Static variables in this context are those which apply to the class, not each object instance.