Static variable
In
In general, static memory allocation is the allocation of memory at
History
Static variables date at least to ALGOL 60 (1960), where they are known as own 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
(1) Static data items:
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 is used in C and related languages both for static variables and other concepts.
Addressing
The
Scope
In terms of
Example
An example of a static local variable in 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;
}
Object-oriented programming
In
Object constants known at compile-time, such as string literals, are usually allocated statically. In object-oriented programming, the virtual method tables of classes are usually allocated statically. A statically defined value can also be global in its scope ensuring the same immutable value is used throughout a run for consistency.
See also
Notes
- ^ Jack Rons. "What is static memory allocation and dynamic memory allocation?". MeritHub [An Institute of Career Development]. Retrieved 2011-06-16.
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.
[dead link]
References
- ISBN 0-13-110362-8.
- ISBN 0-201-70073-5)