Local variable: Difference between revisions

Content deleted Content added
m tweak case of links
 
(95 intermediate revisions by 63 users not shown)
Line 1:
{{Short description|Computer programming, a variable only usable in a portion of a program (the scope)}}
In [[computer science]], a '''local variable''' is a [[variable]] that is given ''local [[scope (programming)|scope]]''. Such a variable is accessible only from the [[subroutine|function]] or [[statement block|block]] in which it is declared. Local variables are contrasted with [[global variables]].
In [[computer science]], a '''local variable''' is a [[Variable (programming)|variable]] that is given ''local [[scope (programming)|scope]]''. A local variable reference in the [[subroutine|function]] or [[block (programming)|block]] in which it is declared overrides the same variable name in the larger scope. In [[programming language]]s with only two levels of visibility, local variables are contrasted with [[global variables]]. On the other hand, many [[ALGOL]]-derived languages allow any number of nested levels of visibility, with private variables, functions, constants and types hidden within them, either by nested blocks or [[nested function]]s. Local variables are fundamental to [[procedural programming]], and more generally [[modular programming]]: variables of local scope are used to avoid issues with [[side-effect (computer science)|side-effects]] that can occur with [[global variable]]s.
 
==Scope==
In most languages, local variables are [[automatic variable]]s stored on the [[call stack]] directly. This means that when a [[recursion (computer science)|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]] to processes outside of the block in which they are declared.
Local variables may have a lexical or dynamic [[scope (programming)|scope]], though lexical (static) scoping is far more common. In lexical scoping (or lexical scope; also called static scoping or static scope), if a variable name's scope is a certain block, then its scope is the program text of the block definition: within that block's text, the variable name exists, and is bound to the variable's value, but outside that block's text, the variable name does not exist. By contrast, in dynamic scoping (or dynamic scope), if a variable name's scope is a certain block, then its scope is that block and all functions transitively called by that block (except when overridden again by another declaration); after the block ends, the variable name does not exist. Some languages, like [[Perl]] and [[Common Lisp]], allow the programmer to choose static or dynamic scoping when defining or redefining a variable. Examples of languages that use dynamic scoping include [[Logo (programming language)|Logo]], [[Emacs lisp]], and the shell languages [[Bash (Unix shell)|bash]], [[dash (shell)|dash]], and the MirBSD Korn shell ([[mksh]])'s "local" declaration. Most other languages provide lexically scoped local variables.
 
In most languages, local variables are [[automatic variable]]s stored on the [[call stack]] directly. This means that when a [[recursion (computer science)|recursive function]] calls itself, local variables in each instance of the function are given separate memorydistinct [[addressMemory spaceaddress|addresses]]. Hence variables of this scope can be declared, written to, and read, without any risk of [[side-effect (computer science)|side-effects]] to processesfunctions outside of the block in which they are declared.
 
Programming languages that employ ''[[call by value]]'' semantics provide a called subroutine with its own local copy of the [[function argument|arguments]] passed to it. In most languages, these local parameters are treated the same as other local variables within the subroutine. In contrast, ''[[call by reference]]'' and ''[[call by name]]'' semantics allow the parameters to act as aliases of the values passed as arguments, allowing the subroutine to modify variables outside its own scope.
 
Some advocate that all variables should be of local scope to avoid issues with [[side-effect (computer science)|side-effects]].
 
==Static local variables==
A special type of local variable, called a ''static local,'' is available in many mainstream languages, (including [[C (programming language)|C]]/[[C++]], [[Visual Basic]] and, [[Visual Basic (.NET)|VB.NET]], and [[PHP]]) which allows a value to be retained from one call of the function to another – it is a [[static variable]] with local scope. In this case, recursive calls to the function also have access to the (single, [[static memory allocation|statically allocated]]) variable. In all of the above languages, static variables are declared as such with a special ''storage class'' keyword (e.g., <code>static</code>).
{{main|Static variable}}
A special type of local variable, called a static local, is available in many mainstream languages, including [[C (programming language)|C]]/[[C++]], [[Visual Basic]] and [[Visual Basic .NET|VB.NET]], which allows a value to be retained from one call of the function to another. In this case, recursive calls to the function also have access to the variable. In all of the above languages, variables are declared as such with a special ''storage class'' keyword (e.g., <code>static</code>).
 
Static locals in global functions canhave bethe thoughtsame oflifetime as [[static global variablesvariable]]s, because their value remains in memory for the life of the program.,<ref>{{PDFlinkcite web|[url= http://www.open-std.org/JTC1/SC22/WG14/www/docs/n1256.pdf |title=Current C standard] }}&nbsp;{{small|(3.61&nbsp;MB<!-- application/pdf, 3788603 bytes -->)}} ({{As of|20082009|lc=on}}). In particular, see section 6.2.4 “Storage durations of objects”, page 32.</ref> Thebut only difference is that they are only accessible through onehave [[function. Staticscope]] locals(not canglobal alsoscope), beas declaredwith inautomatic class-levellocal functions in [[object-oriented programming|object-oriented]] languagesvariables.
 
Note: This is distinct from other usages of the [[Static (keyword)|<code>static</code> keyword]], which has several different meanings in various other languages.
Stricter and more formal [[Object-oriented programming|object-oriented]] languages such as [[Java (programming language)|Java]] and [[C Sharp (programming language)|C#]], do not allow local variables to be declared static to a function.
Instead, "static" variables in these languages are scoped to the class.
 
==Local variables in Perl==
Note: This is distinct from other usages of the <code>static</code> keyword, which has several different meanings in various other languages.
 
[[Perl]] hassupports aboth dynamic and lexically-scoped local variables. The keyword, <code>local</code> is used to define local dynamically-scoped variables, while <code>my</code> is used for “localizing”local lexically-scoped variables,. but inSince thisdynamic casescoping is less common today, the Perl documentation warns that "<code>local</code> isn't what most people think of as “local”.".<ref>[http://perldoc.perl.org/functions/local.html perldoc.perl.org: local]</ref> It Instead, the <code>local</code> keyword gives a temporary, [[scope (programmingcomputer science)|dynamically-scoped]] value to a global (package) variable, which lasts until the end of the enclosing block. However, the variable is visible to any function called from within the block.<ref>[http://perldoc.perl.org/perlsub.html#Temporary-Values-via-local() perldoc.perl.org: perlsub: Temporary Values via <code>local()</code>]</ref> To create lexically-scoped local variables, use the <code>my</code> operator instead.<ref>[http://perldoc.perl.org/perlsub.html#Private-Variables-via-my() perldoc.perl.org: perlsub: Private Variables via <code>my()</code>]</ref>
==<code>local</code> in Perl==
 
To understand how it works consider the following code:
[[Perl]] has a keyword, <code>local</code>, for “localizing” variables, but in this case, <code>local</code> isn't what most people think of as “local”.<ref>[http://perldoc.perl.org/functions/local.html perldoc.perl.org: local]</ref> It gives a temporary, [[scope (programming)|dynamically-scoped]] value to a global (package) variable, which lasts until the end of the enclosing block. However, the variable is visible to any function called from within the block.<ref>[http://perldoc.perl.org/perlsub.html#Temporary-Values-via-local() perldoc.perl.org: perlsub: Temporary Values via <code>local()</code>]</ref>
<syntaxhighlight lang="perl">
$a = 1;
sub f() {
local $a;
$a = 2;
g();
}
sub g() {
print "$a\n";
}
g();
f();
g();
</syntaxhighlight>
 
this will output:
To create lexical variables, which are more like the automatic variables discussed above, use the <code>my</code> operator instead.<ref>[http://perldoc.perl.org/perlsub.html#Private-Variables-via-my() perldoc.perl.org: perlsub: Private Variables via <code>my()</code>]</ref>
1
2
1
 
This happens since the global variable $a is modified to a new ''temporary'' (local) meaning inside {{code|f()}}, but the global value is restored upon leaving the scope of {{code|f()}}.
==References==
<references />
 
Using <code>my</code> in this case instead of <code>local</code> would have printed 1 three times since in that case the <code>$a</code> variable would be limited to the static scope of the function {{code|f()}} and not seen by {{code|g()}}.<br /> Randal L. Schwartz and Tom Phoenix argue that the operator <code>local</code> should have had a different name like <code>save</code>.<ref>{{cite book|author=Randal L. Schwartz and Tom Phoenix|title=Learning Perl 3rd edition|at=paragraph 4.7|publisher=O'REILLY|date=2001-07-01|ISBN=0-596-00132-0|url=https://archive.org/details/learningperl00schw}}</ref>
 
==Local variables in Ruby==
{{compu-prog-stub}}
[[Ruby (programming language)|Ruby]] as a language was inspired also by Perl, but in this case, the notation was made simpler: a global variable name must be preceded by a $ sign, like <code>$variable_name</code>, while a local variable has simply no $ sign in front of its name, like <code>variable_name</code> (while in perl all scalar values have a $ in front). Note that Ruby only provides built-in support for statically-scoped local variables like Perl's <code>my</code>, not dynamically-scoped local variables like Perl's <code>local</code>. There is at least one library for Ruby that provides dynamically-scoped variables.
<ref>
Conrad Irwin.
"LSpace: Dynamic scope for Ruby".
December 2012
http://cirw.in/blog/lspace
Retrieved 2013-10-16.
</ref>
 
== See also ==
[[fr:Variable locale]]
* [[Global variable]]
[[is:Staðvær breyta]]
* [[Non-local variable]]
[[ja:ローカル変数]]
 
==References==
<references />
 
{{DEFAULTSORT:Local Variable}}
[[Category:Variable (computer programmingscience)]]