Scope (computer programming) ============================ In computer programming, the scope of a name binding (an association of a name to an entity, such as a variable) is the part of a program in which the name binding is valid. In other words, a scope is where a name can be used to refer to an entity. In other parts of the program, the name may refer to a different entity (it may have a different binding), or to nothing at all (it may be unbound). 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. The term "scope" is also used to refer to the set of all name bindings that are valid within a part of a program or at a given point in a program, which is more correctly referred to as context or environment. Strictly speaking and in practice for most programming languages, "part of a program" refers to a portion of source code (area of text), and is known as lexical scope. In some languages, however, "part of a program" refers to a portion of run time (period during execution), and is known as dynamic scope.… In computer programming, the scope of a name binding (an association of a name to an entity, such as a variable) is the part of a program in which the name binding is valid. In other words, a scope is where a name can be used to refer to an entity. In other parts of the program, the name may refer to a different entity (it may have a different binding), or to nothing at all (it may be unbound). 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. The term "scope" is also used to refer to the set of all name bindings that are valid within a part of a program or at a given point in a program, which is more correctly referred to as context or environment. Strictly speaking and in practice for most programming languages, "part of a program" refers to a portion of source code (area of text), and is known as lexical scope. In some languages, however, "part of a program" refers to a portion of run time (period during execution), and is known as dynamic scope. Both of these terms are somewhat misleading—they misuse technical terms, as discussed in the definition—but the distinction itself is accurate and precise, and these are the standard respective terms. Lexical scope is the main focus of this article, with dynamic scope understood by contrast with lexical scope. In most cases, name resolution based on lexical scope is relatively straightforward to use and to implement, as in use one can read backwards in the source code to determine to which entity a name refers, and in implementation one can maintain a list of names and contexts when compiling or interpreting a program. Difficulties arise in name masking, forward declarations, and hoisting, while considerably subtler ones arise with non-local variables, particularly in closures. The scope of a name binding is an expression, which is known as expression scope. Expression scope is available in many languages, especially functional languages which offer a feature called let expressions allowing a declaration's scope to be a single expression. This is convenient if, for example, an intermediate value is needed for a computation. For example, in Standard ML, if f() returns 12 , then let val x = f() in x * x end is an expression that evaluates to 144 , using a temporary variable named x to avoid calling f() twice. Some languages with block scope approximate this functionality by offering syntax for a block to be embedded into an expression; for example, the aforementioned Standard ML expression could be written in Perl as do { my $x = f(); $x * $x } , or in GNU C as ({ int x = f(); x * x; }) . In Python, auxiliary variables in generator expressions and list comprehensions (in Python 3) have expression scope. In C, variable names in a function prototype have expression scope, known in this context as function protocol scope. As the variable names in the prototype are not referred to (they may be different in the actual definition)—they are just dummies—these are often omitted, though they may be used for generating documentation, for instance. int sum_of_squares(int m) { int result = 0; for (int n = 1; n A representative example of the use of block scope is the C code shown here, where two variables are scoped to the loop: the loop variable n , which is initialized once and incremented on each iteration of the loop, and the auxiliary variable n_squared , which is initialized at each iteration. The purpose is to avoid adding variables to the function scope that are only relevant to a particular block—for example, this prevents errors where the generic loop variable i has accidentally already been set to another value. In this example the expression n * n would generally not be assigned to an auxiliary variable, and the body of the loop would simply be written result += n * n but in more complicated examples auxiliary variables are useful. Blocks are primarily used for control flow, such as with if, while, and for loops, and in these cases block scope means the scope of variable depends on the structure of a function's flow of execution. However, languages with block scope typically also allow the use of "naked" blocks, whose sole purpose is to allow fine-grained control of variable scope. For example, an auxiliary variable may be defined in a block, then used (say, added to a variable with function scope) and discarded when the block ends, or a while loop might be enclosed in a block that initializes variables used inside the loop that should only be initialized once. A subtlety of several programming languages, such as Algol 68 and C (demonstrated in this example and standardized since C99), is that block-scope variables can be declared not only within the body of the block, but also within the control statement, if any. This is analogous to function parameters, which are declared in the function declaration (before the block of the function body starts), and in scope for the whole function body. This is primarily used in for loops, which have an initialization statement separate from the loop condition, unlike while loops, and is a common idiom. Block scope can be used for shadowing. In this example, inside the block the auxiliary variable could also have been called n , shadowing the parameter name, but this is considered poor style due to the potential for errors. Furthermore, some descendants of C, such as Java and C#, despite having support for block scope (in that a local variable can be made to go out of context before the end of a function), do not allow one local variable to hide another. In such languages, the attempted declaration of the second n would result in a syntax error, and one of the n variables would have to be renamed. If a block is used to set the value of a variable, block scope requires that the variable be declared outside of the block. This complicates the use of conditional statements with single assignment. For example, in Python, which does not use block scope, one may initialize a variable as such: if c: a = "foo" else: a = "" where a is accessible after the if statement. In Perl, which has block scope, this instead requires declaring the variable prior to the block: my $a; if (c) { $a = 'foo'; } else { $a = ; } Often this is instead rewritten using multiple assignment, initializing the variable to a default value. In Python (where it is not necessary) this would be: a = "" if c: a = "foo" while in Perl this would be: my $a = ; if (c) { $a = 'foo'; } In case of a single variable assignment, an alternative is to use the ternary operator to avoid a block, but this is not in general possible for multiple variable assignments, and is difficult to read for complex logic. This is a more significant issue in C, notably for string assignment, as string initialization can automatically allocate memory, while string assignment to an already initialized variable requires allocating memory, a string copy, and checking that these are successful. { my $counter = 0; sub increment_counter { return ++$counter; } } Some languages allow the concept of block scope to be applied, to varying extents, outside of a function. For example, in the Perl snippet at right, $counter is a variable name with block scope (due to the use of the my keyword), while increment_counter is a function name with global scope. Each call to increment_counter will increase the value of $counter by one, and return the new value. Code outside of this block can call increment_counter , but cannot otherwise obtain or alter the value of $counter . This idiom allows one to define closures in Perl. def square(n: int) -> int: return n * n def sum_of_squares(n: int) -> int: total: int = 0 i: int = 0 while i For example, in the snippet of Python code on the right, two functions are defined: square and sum_of_squares . square computes the square of a number; sum_of_squares computes the sum of all squares up to a number. (For example, square(4) is 4 2  =  16 , and sum_of_squares(4) is 0 2  + 1 2  + 2 2  + 3 2  + 4 2  =  30 .) Each of these functions has a variable named n that represents the argument to the function. These two n variables are completely separate and unrelated, despite having the same name, because they are lexically scoped local variables with function scope: each one's scope is its own, lexically separate function and thus, they don't overlap. Therefore, sum_of_squares can call square without its own n being altered. Similarly, sum_of_squares has variables named total and i ; these variables, because of their limited scope, will not interfere with any variables named total or i that might belong to any other function. In other words, there is no risk of a name collision between these names and any unrelated names, even if they are identical. No name masking is occurring: only one variable named n is in context at any given time, as the scopes do not overlap. By contrast, were a similar fragment to be written in a language with dynamic scope, the n in the calling function would remain in context in the called function—the scopes would overlap—and would be masked ("shadowed") by the new n in the called function. Function scope is significantly more complicated if functions are first-class objects and can be created locally by a function and then returned. In this case any variables in the nested function that are not local to it (unbound variables in the function definition, that resolve to variables in an enclosing context) create a closure, as not only the function itself, but also its context (of variables) must be returned, and then potentially called in a different context. This requires significantly more support from the compiler, and can complicate program analysis. In the C code snippet above, the function name sum_of_squares has global scope (in C, extern linkage). Adding static to the function signature would result in file scope (internal linkage). $ # bash language $ x=1 $ function g() { echo $x ; x=2 ; } $ function f() { local x=3 ; g ; } $ f # does this print 1, or 3? 3 $ echo $x # does this print 1, or 2? 1 Consider, for example, the program on the right. The first line, x=1 , creates a global variable x and initializes it to 1 . The second line, function g() { echo $x ; x=2 ; } , defines a function g that prints out ("echoes") the current value of x , and then sets x to 2 (overwriting the prior value). The third line, function f() { local x=3 ; g ; } defines a function f that creates a local variable x (hiding the identically named global variable) and initializes it to 3 , and then calls g . The fourth line, f , calls f . The fifth line, echo $x , prints out the current value of x . The scope rules determine what this program prints. If the language of this program is one that uses lexical scope, then g prints and modifies the global variable x (because g is defined outside f ), so the program prints 1 and then 2 . By contrast, if this language uses dynamic scope, then g prints and modifies f 's local variable x (because g is called from within f ), so the program prints 3 and then 1 . (As it happens, the language of the program is Bash, which uses dynamic scope; so the program prints 3 and then 1 . If the same code was run with ksh93 which uses lexical scope, the results would be different.) program P; var I:integer; K:char; procedure A; var K:real; L:integer; procedure B; var M:real; begin (*scope P+A+B*) end; (*scope P+A*) end; (*scope P*) end. For example, Pascal is lexically scoped. Consider the Pascal program fragment at right. The variable I is visible at all points, because it is never hidden by another variable of the same name. The char variable K is visible only in the main program because it is hidden by the real variable K visible only in procedures A and B . Variable L is also visible only in procedure A and B but it does not hide any other variable. Variable M is only visible in procedure B and therefore not accessible either from procedure A or the main program. Also, procedure B is visible only in procedure A and can therefore not be called from the main program. There could have been another procedure named B declared in the program outside of procedure B . The place in the program where " B " is mentioned then determines which of the two procedures named B it represents, analogous with the scope of variables. Correct implementation of lexical scope in languages with first-class nested functions is not trivial, 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 context is called a closure). Depending on implementation and computer architecture, variable lookup may become slightly inefficient when very deeply lexically nested functions are used, although there are well-known techniques to mitigate this. Also, for nested functions that only refer to their own arguments and (immediately) local variables, all relative locations can be known at compile time. No overhead at all is therefore incurred when using that type of nested function. The same applies to particular parts of a program where nested functions are not used, and, naturally, to programs written in a language where nested functions are not available (such as in the C language). define ADD_A(x) x + a will expand to add a to the passed variable, with this name only later resolved by the compiler based on where the macro ADD_A is "called" (properly, expanded). Properly, the C preprocessor only does lexical analysis, expanding the macro during the tokenization stage, but not parsing into a syntax tree or doing name resolution. For example, in the following code, the name a in the macro is resolved (after expansion) to the local variable at the expansion site: define ADD_A(x) (x + a) void add_one(int* x) { const int a = 1; *x = ADD_A(*x); } void add_two(int* x) { const int a = 2; *x = ADD_A(*x); } include int main(void) { char x = 'm'; printf("%c\n", x); { printf("%c\n", x); char x = 'b'; printf("%c\n", x); } printf("%c\n", x); } The program outputs: m m b m There are other levels of scope in C. Variable names used in a function prototype have function prototype visibility, and exit context at the end of the function prototype. Since the name is not used, this is not useful for compilation, but may be useful for documentation. Label names for GOTO statement have function scope. a = 1; function f() { alert(a); var a = 2; } f(); Further, as functions are first-class objects in JavaScript and are frequently assigned as callbacks or returned from functions, when a function is executed, the name resolution depends on where it was originally defined (the lexical context of the definition), not the lexical context or execution context where it is called. The nested scopes of a particular function (from most global to most local) in JavaScript, particularly of a closure, used as a callback, are sometimes referred to as the scope chain, by analogy with the prototype chain of an object. Closures can be produced in JavaScript by using nested functions, as functions are first-class objects. Returning a nested function from an enclosing function includes the local variables of the enclosing function as the (non-local) lexical context of the returned function, yielding a closure. For example: function newCounter() { // return a counter that is incremented on call (starting at 0) // and which returns its new value var a = 0; var b = function() { a++; return a; }; return b; } c = newCounter(); alert(c() + ' ' + c()); // outputs "1 2" Closures are frequently used in JavaScript, due to being used for callbacks. Indeed, any hooking of a function in the local context as a callback or returning it from a function creates a closure if there are any unbound variables in the function body (with the context of the closure based on the nested scopes of the current lexical context, or "scope chain"); this may be accidental. When creating a callback based on parameters, the parameters must be stored in a closure, otherwise it will accidentally create a closure that refers to the variables in the enclosing context, which may change. Name resolution of properties of JavaScript objects is based on inheritance in the prototype tree—a path to the root in the tree is called a prototype chain—and is separate from name resolution of variables and functions. def f() -> None: print(x) x: str = "global" f() prints: global Note that x is defined before f is called, so no error is raised, even though it is defined after its reference in the definition of f . Lexically this is a forward reference, which is allowed in Python. Here assignment creates a new local variable, which does not change the value of the global variable: def f() -> None: x: str = "f" print(x) x: str = "global" print(x) prints: global f() prints: f print(x) prints: global Assignment to a variable within a function causes it to be declared local to the function, hence its scope is the entire function, and thus using it prior to this assignment raises an error. This differs from C, where the scope of the local variable start at its declaration. This code raises an error: def f() -> None: print(x) x: str = "f" x: str = "global" f() Traceback (most recent call last): File " ", line 1, in File " ", line 2, in f UnboundLocalError: local variable 'x' referenced before assignment The default name resolution rules can be overridden with the global or nonlocal (in Python 3) keywords. In the below code, the global x declaration in g means that x resolves to the global variable. It thus can be accessed (as it has already been defined), and assignment assigns to the global variable, rather than declaring a new local variable. Note that no global declaration is needed in f —since it does not assign to the variable, it defaults to resolving to the global variable. def f() -> None: print(x) def g() -> None: global x print(x) x = "g" x: str = "global" f() prints: global g() prints: global f() prints: g global can also be used for nested functions. In addition to allowing assignment to a global variable, as in an unnested function, this can also be used to access the global variable in the presence of a nonlocal variable: def f() -> None: def g() -> None: global x print(x) x: str = "f" g() x: str = "global" f() prints: global For nested functions, there is also the nonlocal declaration, for assigning to a nonlocal variable, similar to using global in an unnested function: def f() -> None: def g() -> None: nonlocal x # Python 3 only x = "g" x: str = "f" g() print(x) x: str = "global" f() prints: g print(x) prints: global a Functions have access to scope they were created in: a Variables created or modified within a function stay there: a Variables created or modified within a function stay there unless assignment to enclosing scope is explicitly requested: a Although R has lexical scope by default, function scopes can be changed: a REFERENCES ---------- BIBLIOGRAPHY (BibTeX) -------------------- @article{ref0, title = {Scope (computer programming)}, url = {https://encyclopegia.org/a/scope-computer-programming} } BIBLIOGRAPHY (RIS) ------------------- TY - JOUR TI - Scope (computer programming) UR - https://encyclopegia.org/a/scope-computer-programming ER - CITE THIS ARTICLE ---------------- Cite this article: Scope (computer programming) Derived from: https://en.wikipedia.org/w/index.php?oldid=1378180074 Licence: CC BY-SA 4.0 Snapshot: enwiki-001378180074 Permalink: /a/scope-computer-programming