All Topics  
Scope (programming)

 

   Email Print
   Bookmark   Link






 

Scope (programming)



 
 
In computer programming
Computer programming

Computer programming is the process of writing, testing, debugging/troubleshooting, and maintaining the source code of computer programs. This source code is written in a programming language....
, scope is an enclosing context where values and expressions are associated. Various programming languages have various types of scopes. The type of scope determines what kind of entities it can contain and how it affects them -- or semantics
Formal semantics of programming languages

In theoretical computer science, formal semantics is the field concerned with the rigorous mathematical study of the meaning of programming languages and models of computation....
. Typically, scope is used to define the visibility and reach of information hiding
Information hiding

Information hiding in computer science is the principle of hiding of design decisions in a computer program that are most likely to change, thus protecting other parts of the program from change if the design decision is changed....
. Scopes can:



A namespace is a scope that uses the enclosing nature of the scope to group logically related identifiers under a single identifier.






Discussion
Ask a question about 'Scope (programming)'
Start a new discussion about 'Scope (programming)'
Answer questions from other users
Full Discussion Forum



Encyclopedia


In computer programming
Computer programming

Computer programming is the process of writing, testing, debugging/troubleshooting, and maintaining the source code of computer programs. This source code is written in a programming language....
, scope is an enclosing context where values and expressions are associated. Various programming languages have various types of scopes. The type of scope determines what kind of entities it can contain and how it affects them -- or semantics
Formal semantics of programming languages

In theoretical computer science, formal semantics is the field concerned with the rigorous mathematical study of the meaning of programming languages and models of computation....
. Typically, scope is used to define the visibility and reach of information hiding
Information hiding

Information hiding in computer science is the principle of hiding of design decisions in a computer program that are most likely to change, thus protecting other parts of the program from change if the design decision is changed....
. Scopes can:

  • contain declarations
    Declaration (computer science)

    In programming languages, a declaration specifies the identifier, Type system, and other aspects of language elements such as Variable#Computer_programming and Subroutine....
     or definitions of identifier
    Identifier

    In computer science, Identifiers are Lexical Token s that name entity. The concept is analogy to that of a "name". Identifiers are used extensively in virtually all information processing systems....
    s;
  • contain statement
    Statement (programming)

    In computer programming a statement can be thought of as the smallest standalone element of an imperative programming language. A program is formed by a sequence of one or more statements....
    s and/or expression
    Expression (programming)

    An expression in a programming language is a combination of value s, variables, operator s, and function s that are interpreted according to the particular Order of operations and of association for a particular programming language, which computes and then produces another value....
    s which define an executable algorithm
    Algorithm

    In mathematics, computing, linguistics and related subjects, an algorithm is a sequence of finite instructions, often used for calculation and data processing....
     or part thereof;
  • nest or be nested.


A namespace is a scope that uses the enclosing nature of the scope to group logically related identifiers under a single identifier. Thus, scopes can affect the name resolution
Name resolution

In computer science, name resolution can have one of several meanings, discussed below....
 for their contents.

Variables are associated with scopes
Variable

A variable is a symbol that stands for a value that may vary; the term usually occurs in opposition to constant, which is a symbol for a non-varying value, i.e....
. Different scoping types affect how local variables are bound
Name binding

In programming languages, name binding is the association of Value s with identifiers. An identifier bound to a value is said to Reference that value....
. This has different consequences depending if the language has static (lexical) or dynamic scoping.

History


Static scoping (also known as lexical scoping) was first introduced in Lisp 1.5 (via the FUNARG device developed by Steve Russell
Steve Russell

Steve "Slug" Russell is a programmer and computer scientist most famous for creating Spacewar!, one of the earliest videogames, in 1961 with the fellow members of the Tech Model Railroad Club at MIT working on a Digital Equipment Corporation Digital PDP-1....
, working under John McCarthy
John McCarthy (computer scientist)

John McCarthy , is an United States computer scientist and cognitive scientist who received the Turing Award in 1971 for his major contributions to the field of Artificial Intelligence ....
) and added later into Algol 60 (also by Steve Russell), and has been picked up in other languages since then. Descendants of dynamically scoped languages often adopt static scoping. Emacs Lisp
Emacs Lisp

Emacs Lisp is a dialect of the Lisp programming language used by the GNU Emacs and XEmacs text editors . It is used for implementing most of the editing functionality built into Emacs, the remainder being written in C ....
, for example, uses dynamic scoping, Common Lisp
Common Lisp

Common Lisp, commonly abbreviated CL, is a dialect of the Lisp programming language, published in American National Standards Institute standard document Information Technology - Programming Language - Common Lisp, formerly X3.226-1994 ....
 has both dynamic and static scoping, and Scheme uses static scoping exclusively. The original Lisp used dynamic scoping. In other cases, languages which already had dynamic scoping have added static scoping afterwards, such as Perl
Perl

In computer programming, Perl is a high-level programming language, List of programming languages by category, Interpreter , dynamic programming language....
. C
C (programming language)

C is a general-purpose computer programming language originally developed in 1972 by Dennis Ritchie at the Bell Telephone Laboratories to implement the Unix operating system....
 and Pascal have always had static scoping, since they are both influenced by the ideas that went into Algol.

Example

The following example shows various scopes declared in the language C#: namespace N



Static versus dynamic scoping

One of the basic reasons for scoping is to keep variables in different parts of the program distinct from one another. Since there are only a small number of short variable names, and programmers share habits about the naming of variables (e.g., i for an array index), in any program of moderate size the same variable name will be used in multiple different scopes. The question of how to match various variable occurrences to the appropriate binding
Name binding

In programming languages, name binding is the association of Value s with identifiers. An identifier bound to a value is said to Reference that value....
 sites is generally answered in one of two ways: static scoping and dynamic scoping.

Static scoping (also known as lexical scoping)

With static scope, a variable always refers to its top-level environment. This is a property of the program text and unrelated to the runtime call stack
Call stack

In computer science, a call stack is a dynamic Stack data structure that stores information about the active subroutines of a computer program....
. Because matching a variable to its binding only requires analysis of the program text, this type of scoping is sometimes also called lexical scoping. Static scope is standard in modern functional languages such as ML
ML programming language

ML is a general-purpose functional programming language developed by Robin Milner and others in the late 1970s at the University of Edinburgh, whose syntax is inspired by ISWIM....
 and Haskell
Haskell (programming language)

Haskell is a standardized, purely functional programming language with non-strict programming language, named after logician Haskell Curry. The goals of the language are described as:...
 because it allows the programmer to reason as if variable bindings are carried out by substitution. Static scoping also makes it much easier to make modular code and reason about it, since its binding structure can be understood in isolation. In contrast, dynamic scope forces the programmer to anticipate all possible dynamic contexts in which the module's code may be invoked.

For example, consider the following program fragment (in Pascal):

Program A; Var I:Integer; K:Char; R:Real; Procedure B; Var K:Real; L:Integer; Procedure C; Var M:Real; Begin // (1) End; Begin // (2) End; Begin // (3) end.

In the above code, the variable I is accessible as an Integer at points (1), (2) and (3) in the program because its scope is global, and is not overridden by another variable of the same name. The variable K is accessible as a Real at points (1) and (2) and as a character at (3). Also, because of the scope of K, the variable called K in C (at point (1)) and B (at point (2)) is not the same variable K in the main program at point (3). Variable L is accessible only in procedure C at point (1) and procedure B at point (2), and is not accessible from the main program. Variable M is only accessible in procedure C at point (1), and is not accessible either from Procedure B or the main program. Also, procedure C can only be called from Procedure B; it cannot be called from the main program. Also, there could be yet another procedure C declared later in the program, and a reference to that procedure would be dependent upon where in the program code as to which procedure is being called, same as to which variable is being referenced in the above example.

Correct implementation of static scope in languages with first-class nested functions can be subtle, as it requires each function value to carry with it a record of the values of the variables that it depends on (the pair of the function and this environment is called a closure
Closure (computer science)

In computer science, a closure is a function that is evaluated in an environment containing one or more bound variables. When called, the function can access these variables....
). When first-class nested functions are not used or not available (such as in C), this overhead is of course not incurred. Variable lookup is always very efficient with static scope, as the location of each value is known at compile time
Compile time

In computer science, compile time refers to either the operations performed by a compiler , programming language requirements that must be met by source code for it to be successfully compiled , or properties of the program that can be reasoned about at compile time....
.

Dynamic scoping


With dynamic scope, each identifier has a global stack
Stack

Stack may refer to:...
 of bindings. Introducing a local variable with name x pushes a binding onto the global x stack (which may have been empty), which is popped off when the control flow
Control flow

In computer science control flow refers to the order in which the individual statement , Instruction or function calls of an imperative programming or functional programming computer program are execution or evaluated....
 leaves the scope. Evaluating x in any context always yields the top binding. In other words, a global identifier refers to the identifier associated with the most recent environment. Note that this cannot be done at compile time because the binding stack only exists at runtime
Runtime

In computer science, runtime or run time describes the operation of a computer program, the duration of its execution, from beginning to termination ....
, which is why this type of scoping is called dynamic scoping.

Generally, certain blocks are defined to create bindings whose lifetime is the execution time of the block; this adds some features of static scoping to the dynamic scoping process. However, since a section of code can be called from many different locations and situations, it can be difficult to determine at the outset what bindings will apply when a variable is used (or if one exists at all). This can be beneficial; application of the principle of least knowledge suggests that code avoid depending on the reasons for (or circumstances of) a variable's value, but simply use the value according to the variable's definition. This narrow interpretation of shared data can provide a very flexible system for adapting the behavior of a function to the current state (or policy) of the system. However, this benefit relies on careful documentation of all variables used this way as well as on careful avoidance of assumptions about a variable's behavior, and does not provide any mechanism to detect interference between different parts of a program. As such, dynamic scoping can be dangerous and almost no modern languages use it. Some languages, like Perl
Perl

In computer programming, Perl is a high-level programming language, List of programming languages by category, Interpreter , dynamic programming language....
 and Common Lisp
Common Lisp

Common Lisp, commonly abbreviated CL, is a dialect of the Lisp programming language, published in American National Standards Institute standard document Information Technology - Programming Language - Common Lisp, formerly X3.226-1994 ....
, allow the programmer to choose static or dynamic scoping when (re)defining a variable. Logo
Logo (programming language)

Logo is a computer programming language used for functional programming. It is an adaptation and dialect of the Lisp language; some have called it Lisp without the S-expression....
 and Emacs lisp
Emacs Lisp

Emacs Lisp is a dialect of the Lisp programming language used by the GNU Emacs and XEmacs text editors . It is used for implementing most of the editing functionality built into Emacs, the remainder being written in C ....
 are some of the few languages that use dynamic scoping.

Dynamic scoping is fairly easy to implement. To find an identifier's value, the program can traverse the runtime stack, checking each activation record (each function's stack frame) for a value for the identifier. This is known as deep binding. An alternate strategy that is usually more efficient is to maintain a stack of bindings for each identifier; the stack is modified whenever the variable is bound or unbound, and a variable's value is simply that of the top binding on the stack. This is called shallow binding. Note that both of these strategies assume a last-in-first-out (LIFO) ordering to bindings for any one variable; in practice all bindings are so ordered.

Example


This example compares the consequences of using static scope and dynamic scope. Observe the following code, in a C-like language:

int x = 0; int f int g

With static scoping, calling g will return 0 since it has been determined at compile time that the expression x in any invocation of f will yield the global x binding which is unaffected by the introduction of a local variable of the same name in g.

With dynamic scoping, the binding stack for the x identifier will contain two items when f is invoked from g: the global binding to 0, and the binding to 1 introduced in g (which is still present on the stack since the control flow hasn't left g yet). Since evaluating the identifier expression by definition always yields the top binding, the result is 1.

In the language Perl
Perl

In computer programming, Perl is a high-level programming language, List of programming languages by category, Interpreter , dynamic programming language....
, variables can be defined with either static or dynamic scoping. Perl's keyword "my" defines a statically scoped local variable, while the keyword "local" defines dynamically scoped local variable. This allows for further clarification with practical examples of each scoping model.

$x = 0; sub f sub g print g."\n";

The example above uses "my" for static scoping of g's local variable $x. As above, calling g returns 0 because f cannot see g's variable $x, so it looks for the global $x.

$x = 0; sub f sub g print g."\n";

In this alternative, "local" is used to make g's $x dynamically-scoped. Now, calling g yields 1 because f sees g's local variable by looking up the execution stack.

In other words, the dynamically-scoped variable $x is resolved in the environment of execution, rather than the environment of definition.

See also


  • Closure (computer science)
    Closure (computer science)

    In computer science, a closure is a function that is evaluated in an environment containing one or more bound variables. When called, the function can access these variables....
  • Global variable
    Global variable

    In computer programming, a global variable is a variable that is accessible in every scope . Interaction mechanisms with global variables are called global environment mechanisms....
  • Local variable
    Local variable

    In computer science, a local variable is a variable that is given local scope . Such a variable is accessible only from the subroutine or statement block in which it is declared....
  • Name binding
    Name binding

    In programming languages, name binding is the association of Value s with identifiers. An identifier bound to a value is said to Reference that value....
  • Name resolution
    Name resolution

    In computer science, name resolution can have one of several meanings, discussed below....
  • Variables (scope and extent)
    Variable

    A variable is a symbol that stands for a value that may vary; the term usually occurs in opposition to constant, which is a symbol for a non-varying value, i.e....
  • Information hiding
    Information hiding

    Information hiding in computer science is the principle of hiding of design decisions in a computer program that are most likely to change, thus protecting other parts of the program from change if the design decision is changed....


External links


  • A blogpost on Lexical scoping in Javascript by Kartik bansal