In computer science, a local variable is a variable that is given local scope. A local variable reference in the function or block in which it is declared overrides the same variable name in the larger scope. In programming languages 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 functions. Local variables are fundamental to procedural programming, and more generally modular programming: variables of local scope are used to avoid issues with side-effects that can occur with global variables.
YouTube Encyclopedic
-
1/3Views:33 76736 57134 864
-
Local and Global Variables | Computer Programming | Khan Academy
-
Java - Local Variables
-
Python Programming Tutorial #19 - Global vs Local Variables
Transcription
Now that you've mastered the basics of functions, I want to talk about a topic that can get a little tricky: the difference between local and global variables. These terms may not mean anything to you now. So let's start with an example. I made this program here to show you how many inches I grew in my childhood. Since humans grow at different rates, I came up with this function, calcInches, where I can pass in a startAge and an endAge, and an inchesPerYear, and then it would calculate how many inches total were grown during that time. . . . and return it back to whoever called it. So you can see here from 0 to 8 years I call calcInches and I pass 0, 8, and 2.5, because I grew about 2.5 inches per year. And so it does a calculation, and you can see it spits out 20. Then from 8 to 16, I call it from, and I pass it 8 and 16 and then 2 because I didn't quite grow as much, and you can see it spits out 16. So this is neat, but now I want to actually display how many inches I grew, total, in my whole childhood. So how do I do that? Well, I might start by looking at my code and thinking, hmmmm, what values do I have here? Do I have anything that looks like it represents total inches? Well, I do have this totalInches variable inside my calcInches function, so I could just output that, see what it says; start there. So let's say text(totalInches, 10, 200), and put it down at the bottom. All right, let's see, what have we got? Oh, o-oh, we've got the 'Oh noes!' guy. And he says there's a problem. totalInches is not defined. Well, that's weird, because we defined totalInches right here, right? var totalInches =. Well, the problem is that we declared totalInches inside a function. On this line here. And when we declare a variable inside a function, it's considered a local variable. It lives only inside this function here (calcInches). And the code outside the function, all of this, it doesn't see local variables inside functions. It only sees whatever gets returned. It only sees that value, not that variable. So when we try to use totalInches outside the function, it doesn't know what it is, and it says 'Hey, I've never seen this variable before. It's not defined. I can't display it.' So there is a way that we can make it so that the outside code can see this variable. And that's if we turn it from a local variable into a global variable. We can do that by moving the definition outside of the function, into what's called the global scope. And now, inside the function, all we're doing is changing the value of it each time, not defining and declaring it. So you can see that it says 'Total grown over life: 16' So it found the variable because we made it into a global variable. But it's not actually the value that we're looking for. That's just the most recent value. And that's because every time we call this function, it's setting totalInches to whatever it's calculating that time. Right? So what we really want to do is, we want a new variable that we use only for storing the overall total that we add to every time we calculate. . .you know, the total for a range. So let's change this back to being a local variable, and let's make a new global variable called lifeInches. And we'll start it at 0. And then inside the function, we'll add to this global variable by saying lifeInches += totalInches. So we're going to add however much we calculate each time we call this function, we're going to add it to the lifeInches global variable. And then at the bottom, we'll display lifeInches: text(lifeInches, 10, 200). Tada! our total growth over life. Now that's not actually how tall I am. I'm taller than that. But that's because you know, we start off born with more than 0 length. So if I want total, maybe I could start at 20. And there you go, that's how tall I am. All right. So let's review, totalInches is what we call a local variable. And we know that because we see the declaration of it inside this function and not outside the function. And so that means that this outside code here doesn't know about this variable called totalInches. Now lifeInches is what we call a global variable. And we know that because we see its declaration outside of any function, in our global scope. So try to keep this in mind when you're writing your functions and your variables. And think to yourself whether you want a local variable for just your function to use, or global variable for your whole program to use. And don't worry if this is hard to wrap your head around. It's one of the trickiest concepts in programming, and in JavaScript in particular. And it's something you'll get better at as you keep practicing.
Scope
Local variables may have a lexical or dynamic 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, Emacs lisp, and the shell languages bash, 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 variables stored on the call stack directly. This means that when a recursive function calls itself, local variables in each instance of the function are given distinct addresses. Hence variables of this scope can be declared, written to, and read, without any risk of side-effects to functions 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 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.
Static local variables
A special type of local variable, called a static local, is available in many mainstream languages (including C/C++, Visual Basic, 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, statically allocated) variable. In all of the above languages, static variables are declared as such with a special storage class keyword (e.g., static
).
Static locals in global functions have the same lifetime as static global variables, because their value remains in memory for the life of the program,[1] but have function scope (not global scope), as with automatic local variables.
This is distinct from other usages of the static
keyword, which has several different meanings in various languages.
Local variables in Perl
Perl supports both dynamic and lexically-scoped local variables. The keyword local
is used to define local dynamically-scoped variables, while my
is used for local lexically-scoped variables. Since dynamic scoping is less common today, the Perl documentation warns that "local
isn't what most people think of as “local”.".[2] Instead, the local
keyword gives a temporary, 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.[3] To create lexically-scoped local variables, use the my
operator instead.[4]
To understand how it works consider the following code:
$a = 1;
sub f() {
local $a;
$a = 2;
g();
}
sub g() {
print "$a\n";
}
g();
f();
g();
this will output:
1 2 1
This happens since the global variable $a is modified to a new temporary (local) meaning inside f()
, but the global value is restored upon leaving the scope of f()
.
Using my
in this case instead of local
would have printed 1 three times since in that case the $a
variable would be limited to the static scope of the function f()
and not seen by g()
.
Randal L. Schwartz and Tom Phoenix argue that the operator local
should have had a different name like save
.[5]
Local variables in Ruby
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 $variable_name
, while a local variable has simply no $ sign in front of its name, like variable_name
(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 my
, not dynamically-scoped local variables like Perl's local
. There is at least one library for Ruby that provides dynamically-scoped variables.
[6]
See also
References
- ^ "Current C standard" (PDF). (3.61 MB) (as of 2009[update]). In particular, see section 6.2.4 “Storage durations of objects”, page 32.
- ^ perldoc.perl.org: local
- ^ perldoc.perl.org: perlsub: Temporary Values via
local()
- ^ perldoc.perl.org: perlsub: Private Variables via
my()
- ^ Randal L. Schwartz and Tom Phoenix (2001-07-01). Learning Perl 3rd edition. O'REILLY. paragraph 4.7. ISBN 0-596-00132-0.
- ^ Conrad Irwin. "LSpace: Dynamic scope for Ruby". December 2012 http://cirw.in/blog/lspace Retrieved 2013-10-16.