Jump to content

Static (keyword): Difference between revisions

From Wikipedia, the free encyclopedia
Content deleted Content added
BunnysBot (talk | contribs)
m Fix CW Error #61 with GenFixes (T1)
 
(48 intermediate revisions by 32 users not shown)
Line 1: Line 1:
{{Short description|Reserved word in some programming languages}}
{{Multiple issues|
{{More citations needed|date=June 2022}}
{{Missing information|the use of the static keyword to declare class methods in C++ and Java|date=April 2014}}
{{Missing information|the use of the static keyword to declare class methods in C++ and Java|date=April 2014}}
}}
{{lowercase title}}


In the [[C (programming language)|C programming language]] (and its close descendants such as [[C++]] and [[Objective-C]]), '''<code>static</code>''' is a [[reserved word]] controlling both lifetime (as a [[static variable]]) and visibility (depending on ''[[Linkage (software)|linkage]]''). The word <code>static</code> is also used in languages influenced by C, such as [[Java (programming language)|Java]].
'''<code>static</code>''' is a [[reserved word]] in many [[programming language]]s to modify a declaration. The effect of the keyword varies depending on the details of the specific programming language, most commonly used to modify the lifetime (as a [[static variable]]) and visibility (depending on ''[[Linkage (software)|linkage]]''), or to specify a [[class variable|class member]] instead of an instance member in classes.


== Origin ==
In C, <code>static</code> is a [[storage class]] (not to be confused with [[object-oriented programming#Class|classes in object-oriented programming]]), as are '''<code>[[External variable|extern]]</code>''', '''<code>[[Automatic variable#C, C++|auto]]</code>''' and '''<code>[[Automatic variable#C, C++|register]]</code>''' (which are also reserved words). Every variable and function has one of these storage classes; if a declaration does not specify the storage class, a context-dependent default is used:
In the predecessors of C, including [[BCPL]] and [[B (programming language)|B]], there was already a concept of [[static variable|static storage]].,<ref>{{cite web |title=MUL TIC SYSTEf·-1-PROGRAMMERS' MANUAL |url=https://people.csail.mit.edu/saltzer/Multics/Multics-Documents/MSPM/bz-6-04.680712.bcpl-code-generation.pdf}}</ref><ref name="b">{{cite book |last1=Kernighan |first1=B. W |title=A TUTORIAL INTRODUCTION TO THE LANGUAGE B |publisher=Bell Laboratories |location=Murray Hill, New Jersey |page=4 |url=https://www.bell-labs.com/usr/dmr/www/btut.pdf}}</ref> which meant a storage which is always in existence. However, In B, there wasn't a <code>static</code> keyword, but there was an <code>extrn</code> keyword to specify external storage (external to all functions and must be defined outside a function), which is always static, in contrast with <code>auto</code> keyword, which declared an variable with ''auto storage'' - one appears whenever the function is invoked, and disappears when the function is left.<ref name="b"/> All variables must be declared, as one of <code>auto</code>, <code>extrn</code>, or implicitly as function arguments.
*<code>extern</code> for all top-level declarations in a source file,

*<code>auto</code> for variables declared in function bodies.
C was developed as a successor of B, and the <code>static</code> and <code>register</code> keyword were added as [[storage class]] specifiers, alongside with <code>[[Automatic variable#C, C++|auto]]</code> and <code>[[External variable|extern]]</code>, which kept their meaning from B. However, in C, the concept of linkage for variables outside functions was introduced. A C program can be formed by multiple compilation units and linked together to form a complete program, which a variable or a function can be either specified as having ''internal linkage'' (visible to its own compilation unit only), or ''external linkage'' (visible to the whole program). These keywords specify both the storage duration and linkage as follows:<ref>{{cite web |title=Storage-class specifiers |url=https://en.cppreference.com/enwiki/w/c/language/storage_duration |website=cppreference.com}}</ref>


{| class=wikitable
{| class=wikitable
! style="text-align:left" | Storage class
! style="text-align:left" | Storage class
! style="text-align:left" | Lifetime
! style="text-align:left" | Duration
! style="text-align:left" | Visibility
! style="text-align:left" | Linkage
|-
|-
| <code>extern</code>
| <code>extern</code>
| program execution
| [[static variable|static]] (program execution)
| external (whole program)
| external (whole program)
|-
|-
| <code>static</code>
| <code>static</code>
| program execution
| [[static variable|static]] (program execution)
| internal ([[translation unit (programming)|translation unit]] only)
| internal ([[translation unit (programming)|translation unit]] only) for top-level identifier<br>none for block-scope variables
|-
|-
| <code>auto</code>, <code>register</code>
| <code>auto</code>, <code>register</code>
| [[automatic variable|function execution]]
| [[automatic variable|function execution]]
| (none)
| none
|}
|}


Every variable and function has one of these storage classes; if a declaration does not specify the storage class, a context-dependent default is used:
In these languages, the term "static variable" has two meanings which are easy to confuse:
*<code>extern</code> for all top-level declarations in a source file,
*<code>auto</code> for variables declared in function bodies.

So, in C, although the <code>static</code> keyword, when used on variables, always declare a variable with static storage duration, there are two distinct meanings of the keyword, depending on where it is used:
* Top-level declaration: to declare an identifier with internal instead of external linkage, applicable to both variables and functions.
* Block-scoped declaration: to declare a variable with static instead of automatic storage duration. C doesn't support block-scoped functions.

Therefore, in C, the term "static variable" has two meanings which are easy to confuse:
# A variable with the same lifetime as the program, as described above (language-independent); ''or''
# A variable with the same lifetime as the program, as described above (language-independent); ''or''
# (C-family-specific) A variable declared with storage class <code>static</code>.
# (C-family-specific) A variable declared with storage class <code>static</code>.
Variables with storage class <code>extern</code>, which include variables declared at top level without an explicit storage class, are <code>static</code> in the first meaning but not the second.
Variables with storage class <code>extern</code>, which include variables declared at top level without an explicit storage class, are <code>static</code> in the first meaning but not the second.


In C++ (not C), the <code>static</code> keyword can also be used to declare a member variable in a class to have static storage duration as well, independent from the storage duration of the class object itself, and such a variable must be defined outside the class. The effect is that the variable is shared among all class instances, becoming a class member instead of an instance member. When applied to a member function (method), it specifies that the member function operates independently of an instance, which means it can't access any non-static members of the class nor the <code>this</code> pointer.
==Other uses==

As well as specifying static lifetime, declaring a variable as <code>static</code> can have other effects depending on where the declaration occurs:
== As a storage duration specifier ==
;{{visible anchor|Static global variable}}: A variable declared as <code>static</code> at the top level of a source file (outside any function definitions) is only visible throughout that file ("[[file scope]]", also known as "[[internal linkage]]").
The <code>static</code> keyword is used in many programming languages to specify a local variable to have a lifetime of the whole program, preserved between function invocations, instead of having its own copy for each function invocation as in automatic storage duration, inherited from the usage in C.
;[[Static local variable]]s: Variables declared as <code>static</code> inside a function are statically allocated, thus keep their memory cell throughout all program execution, while having the same scope of visibility as [[automatic variable|automatic local variables]] (<code>auto</code> and <code>register</code>), meaning remain local to the function. Hence whatever values the function puts into its static local variables during one call will still be present when the function is called again.

;Static member variables: In [[C++]], member variables declared as <code>static</code> inside class definitions are [[class variable]]s (shared between all class instances, as opposed to [[instance variable]]s).
Examples of programming languages which support the usage of <code>static</code> keyword for local variables to be kept across invocation include such as [[C (programming language)|C]], [[C++]], [[Objective-C]], [[C Sharp (programming language)|C#]], [[PHP]].

The following programming languages with C-like syntax do not support <code>static</code> local variables as in C: [[Java (programming language)|Java]], [[JavaScript]], [[Dart (programming language)|Dart]]. In these languages, a variable which is kept for the whole program execution needs to be declared outside functions.

== As a visibility specifier ==
The <code>static</code> keyword in C, when used as a top-level declaration, makes the variable or function visible to its own compilation unit only. Modern programming languages generally uses [[namespace]]s to avoid name clashes, so this use isn't widely adopted apart from programming languages with C compatibility in mind (e.g. [[C++]], [[Objective-C]]). Other programming languages which support visibility declarations at top-level use a variety of other keywords to specify different level of visibility, for example, <code>public</code> in Java for classes which can be used everywhere, or <code>internal</code> / <code>file</code> in C#.<ref>{{cite web |title=Access Modifiers (C# Programming Guide) |url=https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/access-modifiers |publisher=Microsoft}}</ref>

== As a class member specifier ==
The <code>static</code> keyword is used in most programming languages with classes to specify a member to be a class member, instead of an instance member, inherited from the usage of C++.

A static member of a class has the following characteristics:
* Indepedent from any class instances, can be accessed using the class name instead of an expression having the class object type.
* For fields: exist throughout the program lifetime (i.e. having static storage duration).
* For methods: cannot access any non-static members without an object expression (implicitly referring to the current instance), or the <code>this</code> reference for the current instance.

Some programming languages even go further, allowing the use of <code>static</code> keyword in other places in a class declaration or usage, for example:
* Static initialisers in Java and JavaScript, which are run once when the class is loaded
* Static constructors in C#, which are run once before the class is used
* Static classes in C#, which can't be instantiated.
* Inner classes in Java implicitly carry a <code>this</code> reference to the outer class object and must exist in the context of an outer class instance. By declaring an inner class to be <code>static</code>, it does not carry such a reference and can be used independently to an outer class instance.
* The <code>static</code> keyword can be used in place of an actual class name to access static members to provide class-level polymorphism, called ''late static bindings''<ref>{{cite web |title=Late Static Bindings |url=https://www.php.net/manual/en/language.oop5.late-static-bindings.php |website=PHP Manual}}</ref>

== As a specifier for [[Closure (computer programming)|closure]]s ==
The <code>static</code> keyword can be used in some programming languages on [[anonymous function]]s to prevent capturing states which are captured by default. It is similar to static local variables and static class members in the sense that a static closure does not depend on the running invocation of the containing function.

* PHP: Closures constructed in an instance method have the <code>$this</code> reference automatically bound to it, the <code>static</code> keyword prevents this.
* C#: Closures by default have all local and instance variables captured in it, the <code>static</code> keyword specifies that no outside states to be captured.<ref>{{cite web |title=Static anonymous functions |url=https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-9.0/static-anonymous-functions |publisher=Microsoft}}</ref>

==See also==
{{Portal|Computer programming}}

==References==
{{Reflist}}


[[Category:C (programming language)]]
[[Category:C (programming language)]]
[[Category:C++]]
[[Category:Java (programming language)]]

Latest revision as of 16:27, 10 December 2024


static is a reserved word in many programming languages to modify a declaration. The effect of the keyword varies depending on the details of the specific programming language, most commonly used to modify the lifetime (as a static variable) and visibility (depending on linkage), or to specify a class member instead of an instance member in classes.

Origin

[edit]

In the predecessors of C, including BCPL and B, there was already a concept of static storage.,[1][2] which meant a storage which is always in existence. However, In B, there wasn't a static keyword, but there was an extrn keyword to specify external storage (external to all functions and must be defined outside a function), which is always static, in contrast with auto keyword, which declared an variable with auto storage - one appears whenever the function is invoked, and disappears when the function is left.[2] All variables must be declared, as one of auto, extrn, or implicitly as function arguments.

C was developed as a successor of B, and the static and register keyword were added as storage class specifiers, alongside with auto and extern, which kept their meaning from B. However, in C, the concept of linkage for variables outside functions was introduced. A C program can be formed by multiple compilation units and linked together to form a complete program, which a variable or a function can be either specified as having internal linkage (visible to its own compilation unit only), or external linkage (visible to the whole program). These keywords specify both the storage duration and linkage as follows:[3]

Storage class Duration Linkage
extern static (program execution) external (whole program)
static static (program execution) internal (translation unit only) for top-level identifier
none for block-scope variables
auto, register function execution none

Every variable and function has one of these storage classes; if a declaration does not specify the storage class, a context-dependent default is used:

  • extern for all top-level declarations in a source file,
  • auto for variables declared in function bodies.

So, in C, although the static keyword, when used on variables, always declare a variable with static storage duration, there are two distinct meanings of the keyword, depending on where it is used:

  • Top-level declaration: to declare an identifier with internal instead of external linkage, applicable to both variables and functions.
  • Block-scoped declaration: to declare a variable with static instead of automatic storage duration. C doesn't support block-scoped functions.

Therefore, in C, the term "static variable" has two meanings which are easy to confuse:

  1. A variable with the same lifetime as the program, as described above (language-independent); or
  2. (C-family-specific) A variable declared with storage class static.

Variables with storage class extern, which include variables declared at top level without an explicit storage class, are static in the first meaning but not the second.

In C++ (not C), the static keyword can also be used to declare a member variable in a class to have static storage duration as well, independent from the storage duration of the class object itself, and such a variable must be defined outside the class. The effect is that the variable is shared among all class instances, becoming a class member instead of an instance member. When applied to a member function (method), it specifies that the member function operates independently of an instance, which means it can't access any non-static members of the class nor the this pointer.

As a storage duration specifier

[edit]

The static keyword is used in many programming languages to specify a local variable to have a lifetime of the whole program, preserved between function invocations, instead of having its own copy for each function invocation as in automatic storage duration, inherited from the usage in C.

Examples of programming languages which support the usage of static keyword for local variables to be kept across invocation include such as C, C++, Objective-C, C#, PHP.

The following programming languages with C-like syntax do not support static local variables as in C: Java, JavaScript, Dart. In these languages, a variable which is kept for the whole program execution needs to be declared outside functions.

As a visibility specifier

[edit]

The static keyword in C, when used as a top-level declaration, makes the variable or function visible to its own compilation unit only. Modern programming languages generally uses namespaces to avoid name clashes, so this use isn't widely adopted apart from programming languages with C compatibility in mind (e.g. C++, Objective-C). Other programming languages which support visibility declarations at top-level use a variety of other keywords to specify different level of visibility, for example, public in Java for classes which can be used everywhere, or internal / file in C#.[4]

As a class member specifier

[edit]

The static keyword is used in most programming languages with classes to specify a member to be a class member, instead of an instance member, inherited from the usage of C++.

A static member of a class has the following characteristics:

  • Indepedent from any class instances, can be accessed using the class name instead of an expression having the class object type.
  • For fields: exist throughout the program lifetime (i.e. having static storage duration).
  • For methods: cannot access any non-static members without an object expression (implicitly referring to the current instance), or the this reference for the current instance.

Some programming languages even go further, allowing the use of static keyword in other places in a class declaration or usage, for example:

  • Static initialisers in Java and JavaScript, which are run once when the class is loaded
  • Static constructors in C#, which are run once before the class is used
  • Static classes in C#, which can't be instantiated.
  • Inner classes in Java implicitly carry a this reference to the outer class object and must exist in the context of an outer class instance. By declaring an inner class to be static, it does not carry such a reference and can be used independently to an outer class instance.
  • The static keyword can be used in place of an actual class name to access static members to provide class-level polymorphism, called late static bindings[5]

As a specifier for closures

[edit]

The static keyword can be used in some programming languages on anonymous functions to prevent capturing states which are captured by default. It is similar to static local variables and static class members in the sense that a static closure does not depend on the running invocation of the containing function.

  • PHP: Closures constructed in an instance method have the $this reference automatically bound to it, the static keyword prevents this.
  • C#: Closures by default have all local and instance variables captured in it, the static keyword specifies that no outside states to be captured.[6]

See also

[edit]

References

[edit]
  1. ^ "MUL TIC SYSTEf·-1-PROGRAMMERS' MANUAL" (PDF).
  2. ^ a b Kernighan, B. W. A TUTORIAL INTRODUCTION TO THE LANGUAGE B (PDF). Murray Hill, New Jersey: Bell Laboratories. p. 4.
  3. ^ "Storage-class specifiers". cppreference.com.
  4. ^ "Access Modifiers (C# Programming Guide)". Microsoft.
  5. ^ "Late Static Bindings". PHP Manual.
  6. ^ "Static anonymous functions". Microsoft.