Content deleted Content added
mNo edit summary |
Rearranged, added heading, corrected functional info, researched and corrected/added to static locals (all 6 languages verified by testing) |
||
Line 3:
Local variables are special because in most languages they are stored on the [[function stack]] directly. This means that when a [[recursive function]] calls itself, local variables in each instance of the function are given separate memory [[address space]]. Hence variables of this scope can be declared, written to, and read, without any risk of [[Side-effect (computer science)|side-effects]].
Some advocate that all variables should be of local scope to avoid issues with [[Side-effect (computer science)|side-effects]]. In other cases, programming paradigms and languages themselves, such as the [[functional programming]]
A special type of local variable is available in some languages, such as [[Visual Basic#Visual Basic and VB.NET|Visual Basic.NET]] or [[C Sharp|C#]] which allows a value to be retained from one call of the function to another. The value is only lost when the object containing the variable is destroyed. In this case, recursive calls to the function also have access to the variable. One name for this type of variable is a ''static variable''.▼
==Static local variables==
▲Some programming paradigms and languages, such as [[functional programming]] (and its languages such as [[Haskell programming language|Haskell]]) require all variables to be of local scope, and the functionality of the program is achieved only by passing local variables from one function to another.
▲A special type of local variable, called a static local, is available in
Static locals in global functions can be thought of as global variables, because their value remains in memory for the life of the program. The only difference is that they are only accessible through one function. Static locals can also be declared in class-level functions in the above [[Object-oriented programming|object-oriented]] languages, and the behaviour differs depending on the language:
*In [[C plus plus|C++]], static locals declared in class-level functions are shared across all objects. That is, they act like static class-level variables.
*In [[Visual Basic]] and [[Visual Basic .NET|VB.NET]], static locals declared in class-level functions are local to the object. That is, they act like non-static class-level variables, and each object has its own copy of the variable.
Stricter and more formal [[Object-oriented programming|object-oriented]] languages such as [[Java programming language|Java]] and [[C Sharp|C#]], do not allow local variables to be declared static at all.
Note: This is distinct from other usages of the <code>static</code> keyword, which has several different meanings in various other languages.
{{comp-stub}}
|