Static variable: Difference between revisions

Content deleted Content added
GreenC bot (talk | contribs)
 
(298 intermediate revisions by more than 100 users not shown)
Line 1:
{{short description|Programming variable that persists for the lifetime of the program}}
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.
{{see also|Static (keyword)}}
In [[computer programming]], a '''static variable''' is a [[variable (programming)|variable]] that has been [[memory allocation|allocated]] "statically", meaning that its [[variable lifetime|lifetime]] (or "extent") is the entire run of the program. This is in contrast to shorter-lived [[automatic variable]]s, whose storage is [[stack allocation|stack allocated]] and deallocated on the [[call stack]]; and in contrast to [[dynamic memory allocation|dynamically allocated]] objects, whose storage is allocated and deallocated in [[heap memory]].
 
[[Variable lifetime]] is contrasted with [[Scope (computer science)|scope]] (where a variable can be used): "global" and "local" refer to scope, not lifetime, but scope often implies lifetime. In many languages, [[global variable]]s are always static, but in some languages they are dynamic, while [[local variable]]s are generally automatic, but may be static.
==Static Variables as Constants==
 
In general, '''{{visible anchor|static memory allocation}}''' is the allocation of memory at [[compile time]], before the associated program is executed, unlike [[dynamic memory allocation]] or [[automatic memory allocation]] where memory is allocated as required at [[run time (program lifecycle phase)|run time]].<ref>{{cite web
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.
| access-date = 2011-06-16
| author = Jack Rons
| publisher = MeritHub [An Institute of Career Development]
| title = What is static memory allocation and dynamic memory allocation?
| quote = The compiler allocates required memory space for a declared variable. By using the addressof operator, the reserved address is obtained and this address may be assigned to a pointer variable. Since most of the declared variables have static memory, this way of assigning pointer value to a pointer variable is known as static memory allocation. Memory is assigned during compilation time.
| url = http://www.merithub.com/q/58-static-memory-allocation-dynamic-memory-allocation.aspx| archive-url = https://web.archive.org/web/20100611071852/http://www.merithub.com/q/58-static-memory-allocation-dynamic-memory-allocation.aspx| url-status = dead| archive-date = June 11, 2010}}</ref>
 
==History==
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 date at least to [[ALGOL 60]] (1960), where they are known as '''''own''' variables'':
{{quote
==Static Variables as Local Function Variables==
|A declaration may be marked with the additional declarator '''own.''' This has the following effect: upon a re-entry into the block, the values of '''own''' quantities will be unchanged from their values at the last exit, while the values of declared variables that are not marked with '''own''' is undefined.
|Revised report on ALGOL 60, section "5. Declarations", p. 14}}
This definition is subtly different from a static variable: it only specifies behavior, and hence lifetime, not storage: an own variable can be allocated when a function is first called, for instance, rather than at program load time.
 
The use of the word ''static'' to refer to these variables dates at least to [[BCPL]] (1966), and has been popularized by the [[C programming language]], which was heavily influenced by BCPL. The BCPL definition reads:
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.
{{quote
|(1) Static data items:<br>Those data items whose extents lasts as long as the program execution time; such data items have manifest constant Lvalues. Every static data item must have been declared either in a function or routine definition, in a global declaration or as a label set by colon.
|The BCPL Reference Manual, 7.2 Space Allocation and Extent of Data Items}}
Note that BCPL defined a "dynamic data item" for what is now called an ''automatic'' variable (local, stack-allocated), not for heap-allocated objects, which is the current use of the term ''dynamic allocation''.
 
The [[Static (keyword)|<code>static</code> keyword]] is used in C and related languages both for static variables and other concepts.
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.
 
==Addressing==
==Static Variables as Class Variables==
{{Unreferenced section|date=June 2023}}
The [[absolute address]] [[addressing mode]] can only be used with static variables, because those are the only kinds of variables whose ___location is known by the compiler at compile time. When the program ([[executable]] or [[Library (computing)|library]]) is [[Loader (computing)|loaded]] into memory, static variables are stored in the [[data segment]] of the program's [[Address space (application programming)|address space]] (if initialized), or the [[BSS segment]] (if uninitialized), and are stored in corresponding sections of [[object file]]s prior to loading.
 
==Scope==
[[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.
{{Unreferenced section|date=June 2023}}
{{see also|Variable (computer science)#Scope and extent}}
 
In terms of [[Variable (computer science)#Scope and extent|scope and extent]], static variables have extent the entire run of the program, but may have more limited [[Scope (computer science)|scope]]. A basic distinction is between a ''static global variable'', which has global scope and thus is in context throughout the program, and a ''[[static local variable]],'' which has local scope. A static local variable is different from a local variable as a static local variable is initialized only once no matter how many times the function in which it resides is called and its value is retained and accessible through many calls to the function in which it is declared, e.g. to be used as a count variable. A static variable may also have [[module scope]] or some variant, such as [[internal linkage]] in [[C programming language|C]], which is a form of file scope or module scope.
 
===Example===
An example of a static local variable in C:
<syntaxhighlight lang=c>
#include <stdio.h>
 
void Func() {
static int x = 0;
// |x| is initialized only once across five calls of |Func| and the variable
// will get incremented five times after these calls. The final value of |x|
// will be 5.
x++;
printf("%d\n", x); // outputs the value of |x|
}
 
int main() {
Func(); // prints 1
Func(); // prints 2
Func(); // prints 3
Func(); // prints 4
Func(); // prints 5
 
return 0;
}
</syntaxhighlight>
 
== Object-oriented programming ==
{{Unreferenced section|date=June 2023}}
In [[object-oriented programming]], there is also the concept of a ''[[static member variable]]'', which is a "[[class variable]]" of a statically defined class, i.e., a [[member variable]] of a given class which is shared across all [[class instance|instances]] (objects), and is accessible as a member variable of these objects. 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.
 
Object constants known at compile-time, such as [[string literal]]s, are usually allocated statically. In object-oriented programming, the [[virtual method table]]s of classes are usually allocated statically. A statically defined value can also be [[Global variable|global]] in its scope ensuring the same [[Immutable object|immutable]] value is used throughout a run for consistency.
 
== See also ==
* [[Constant (computer programming)]]
* [[Global variable]]
* [[Static method]]
* [[Thread-local storage]]
 
==Notes==
{{Reflist|2}}
 
== References ==
{{refbegin}}
* {{cite book |title=The C Programming Language |last1=Kernighan |first1=Brian W. |author-link1=Brian Kernighan |last2=Ritchie |first2=Dennis M. |author-link2=Dennis Ritchie |year=1988 |publisher=Prentice Hall PTR |place=Upper Saddle River, NJ |edition=2nd |isbn=0-13-110362-8 |url-access=registration |url=https://archive.org/details/cprogramminglang00bria }}
*''[[The C++ Programming Language]]'' (special edition) by [[Bjarne Stroustrup]] (Addison Wesley, 2000; {{ISBN|0-201-70073-5}})
{{refend}}
 
{{Memory management navbox}}
 
<!--Categories-->
{{DEFAULTSORT:Static Memory Allocation}}
[[Category:Memory management]]
[[Category:Variable (computer science)]]