Local variable

Last updated

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.

Contents

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;subf(){local$a;$a=2;g();}subg(){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

Related Research Articles

<span class="mw-page-title-main">Common Lisp</span> Programming language standard

Common Lisp (CL) is a dialect of the Lisp programming language, published in American National Standards Institute (ANSI) standard document ANSI INCITS 226-1994 (S20018). The Common Lisp HyperSpec, a hyperlinked HTML version, has been derived from the ANSI Common Lisp standard.

<span class="mw-page-title-main">Emacs Lisp</span> Dialect of Lisp used as an Emacs scripting language

Emacs Lisp is a dialect of the Lisp programming language used as a scripting language by Emacs. It is used for implementing most of the editing functionality built into Emacs, the remainder being written in C, as is the Lisp interpreter. Emacs Lisp is also termed Elisp, although there are also older, unrelated Lisp dialects with that name.

In computer science, control flow is the order in which individual statements, instructions or function calls of an imperative program are executed or evaluated. The emphasis on explicit control flow distinguishes an imperative programming language from a declarative programming language.

In computer programming, the scope of a name binding is the part of a program where the name binding is valid; that is, where the name can be used to refer to the entity. In other parts of the program, the name may refer to a different entity, or to nothing at all. Scope helps prevent name collisions by allowing the same name to refer to different objects – as long as the names have separate scopes. The scope of a name binding is also known as the visibility of an entity, particularly in older or more technical literature—this is in relation to the referenced entity, not the referencing name.

In programming languages, a closure, also lexical closure or function closure, is a technique for implementing lexically scoped name binding in a language with first-class functions. Operationally, a closure is a record storing a function together with an environment. The environment is a mapping associating each free variable of the function with the value or reference to which the name was bound when the closure was created. Unlike a plain function, a closure allows the function to access those captured variables through the closure's copies of their values or references, even when the function is invoked outside their scope.

In computer programming, a global variable is a variable with global scope, meaning that it is visible throughout the program, unless shadowed. The set of all global variables is known as the global environment or global state. In compiled languages, global variables are generally static variables, whose extent (lifetime) is the entire runtime of the program, though in interpreted languages, global variables are generally dynamically allocated when declared, since they are not known ahead of time.

In computer programming, a block or code block or block of code is a lexical structure of source code which is grouped together. Blocks consist of one or more declarations and statements. A programming language that permits the creation of blocks, including blocks nested within other blocks, is called a block-structured programming language. Blocks are fundamental to structured programming, where control structures are formed from blocks.

<span class="mw-page-title-main">Raku (programming language)</span> Programming language derived from Perl

Raku is a member of the Perl family of programming languages. Formerly known as Perl 6, it was renamed in October 2019. Raku introduces elements of many modern and historical languages. Compatibility with Perl was not a goal, though a compatibility mode is part of the specification. The design process for Raku began in 2000.

In computer programming, a nested function is a function which is defined within another function, the enclosing function. Due to simple recursive scope rules, a nested function is itself invisible outside of its immediately enclosing function, but can see (access) all local objects of its immediately enclosing function as well as of any function(s) which, in turn, encloses that function. The nesting is theoretically possible to unlimited depth, although only a few levels are normally used in practical programs.

In computer programming, a sigil is a symbol affixed to a variable name, showing the variable's datatype or scope, usually a prefix, as in $foo, where $ is the sigil.

xHarbour is a free multi-platform extended Clipper compiler, offering multiple graphic terminals (GTs), including console drivers, GUIs, and hybrid console/GUIs. xHarbour is backward-compatible with Clipper and supports many language syntax extensions, greatly extended run-time libraries, and extensive third party support.

In computer programming, thread-local storage (TLS) is a memory management method that uses static or global memory local to a thread.

In computer science, a call stack is a stack data structure that stores information about the active subroutines of a computer program. This type of stack is also known as an execution stack, program stack, control stack, run-time stack, or machine stack, and is often shortened to simply "the stack". Although maintenance of the call stack is important for the proper functioning of most software, the details are normally hidden and automatic in high-level programming languages. Many computer instruction sets provide special instructions for manipulating stacks.

In computer programming, an automatic variable is a local variable which is allocated and deallocated automatically when program flow enters and leaves the variable's scope. The scope is the lexical context, particularly the function or block in which a variable is defined. Local data is typically invisible outside the function or lexical context where it is defined. Local data is also invisible and inaccessible to a called function, but is not deallocated, coming back in scope as the execution thread returns to the caller.

this, self, and Me are keywords used in some computer programming languages to refer to the object, class, or other entity of which the currently running code is a part. The entity referred to by these keywords thus depends on the execution context. Different programming languages use these keywords in slightly different ways. In languages where a keyword like "this" is mandatory, the keyword is the only way to access data and methods stored in the current object. Where optional, they can disambiguate variables and functions with the same name.

In computer programming, a variable is an abstract storage location paired with an associated symbolic name, which contains some known or unknown quantity of data or object referred to as a value; or in simpler terms, a variable is a named container for a particular set of bits or type of data. A variable can eventually be associated with or identified by a memory address. The variable name is the usual way to reference the stored value, in addition to referring to the variable itself, depending on the context. This separation of name and content allows the name to be used independently of the exact information it represents. The identifier in computer source code can be bound to a value during run time, and the value of the variable may thus change during the course of program execution.

The Perl virtual machine is a stack-based process virtual machine implemented as an opcodes interpreter which runs previously compiled programs written in the Perl language. The opcodes interpreter is a part of the Perl interpreter, which also contains a compiler in one executable file, commonly /usr/bin/perl on various Unix-like systems or perl.exe on Microsoft Windows systems.

The structure of the Perl programming language encompasses both the syntactical rules of the language and the general ways in which programs are organized. Perl's design philosophy is expressed in the commonly cited motto "there's more than one way to do it". As a multi-paradigm, dynamically typed language, Perl allows a great degree of flexibility in program design. Perl also encourages modularization; this has been attributed to the component-based design structure of its Unix roots, and is responsible for the size of the CPAN archive, a community-maintained repository of more than 100,000 modules.

In programming languages, name resolution is the resolution of the tokens within program expressions to the intended program components.

In computer programming languages, an identifier is a lexical token that names the language's entities. Some of the kinds of entities an identifier might denote include variables, data types, labels, subroutines, and modules.

References

  1. "Current C standard" (PDF). (3.61 MB) (as of 2009). In particular, see section 6.2.4 “Storage durations of objects”, page 32.
  2. perldoc.perl.org: local
  3. perldoc.perl.org: perlsub: Temporary Values via local()
  4. perldoc.perl.org: perlsub: Private Variables via my()
  5. Randal L. Schwartz and Tom Phoenix (2001-07-01). Learning Perl 3rd edition. O'REILLY. paragraph 4.7. ISBN   0-596-00132-0.
  6. Conrad Irwin. "LSpace: Dynamic scope for Ruby". December 2012 http://cirw.in/blog/lspace Retrieved 2013-10-16.