赛派号

买黄金项链什么样的结实 Scope (computer science)

Part of a computer program where a given name binding is valid This article has multiple issues. Please help improve it or discuss these issues on the talk page. (Learn how and when to remove these messages) This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: "Scope" computer science – news · newspapers · books · scholar · JSTOR (December 2008) (Learn how and when to remove this message) This article possibly contains original research. Please improve it by verifying the claims made and adding inline citations. Statements consisting only of original research should be removed. (June 2025) (Learn how and when to remove this message) This article's tone or style may not reflect the encyclopedic tone used on Wikipedia. See Wikipedia's guide to writing better articles for suggestions. (June 2025) (Learn how and when to remove this message) (Learn how and when to remove this message)

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 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 (it may he 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 he 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.[a]

Strictly speaking[b] 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.

Definition[edit]

The strict definition of the (lexical) "scope" of a name (identifier) is unambiguous: lexical scope is "the portion of source code in which a binding of a name with an entity applies". This is virtually unchanged from its 1960 definition in the specification of ALGOL 60. Representative language specifications follow:

ALGOL 60 (1960)[1] The following kinds of quantities are distinguished: simple variables, arrays, labels, switches, and procedures. The scope of a quantity is the set of statements and expressions in which the declaration of the identifier associated with that quantity is valid. C (2007)[2] An identifier can denote an object; a function; a tag or a member of a structure, union, or enumeration; a typedef name; a label name; a macro name; or a macro parameter. The same identifier can denote different entities at different points in the program. [...] For each different entity that an identifier designates, the identifier is visible (i.e., can be used) only within a region of program text called its scope. Go (2013)[3] A declaration binds a non-blank identifier to a constant, type, variable, function, label, or package. [...] The scope of a declared identifier is the extent of source text in which the identifier denotes the specified constant, type, variable, function, label, or package.

Most commonly "scope" refers to when a given name can refer to a given variable—when a declaration has effect—but can also apply to other entities, such as functions, types, classes, labels, constants, and enumerations.

Lexical scope vs. dynamic scope[edit]

A fundamental distinction in scope is what "part of a program" means. In languages with lexical scope (also called static scope), name resolution depends on the location in the source code and the lexical context (also called static context), which is defined by where the named variable or function is defined. In contrast, in languages with dynamic scope, the name resolution depends upon the program state when the name is encountered which is determined by the execution context (also called runtime context, calling context or dynamic context). In practice, with lexical scope a name is resolved by searching the local lexical context, then if that fails, by searching the outer lexical context, and so on; whereas with dynamic scope, a name is resolved by searching the local execution context, then if that fails, by searching the outer execution context, and so on, progressing up the call stack.[4]

Most modern languages use lexical scope for variables and functions, though dynamic scope is used in some languages, notably some dialects of Lisp, some "scripting" languages, and some template languages.[c] Perl 5 offers both lexical and dynamic scope. Functions that use lexically scoped variables are known as closures.

Lexical resolution can be determined at compile time, and is also known as early binding, while dynamic resolution can in general only be determined at run time, and thus is known as late binding.

Related concepts[edit]

In object-oriented programming, dynamic dispatch selects an object method at runtime, though whether the actual name binding is done at compile time or run time depends on the language. De facto dynamic scope is common in macro languages, which do not directly do name resolution, but instead expand in place.

Some programming frameworks like AngularJS use the term "scope" to mean something entirely different than how it is used in this article. In those frameworks, the scope is just an object of the programming language that they use (JaScript in case of AngularJS) that is used in certain ways by the framework to emulate dynamic scope in a language that uses lexical scope for its variables. Those AngularJS scopes can themselves be in context or not in context (using the usual meaning of the term) in any given part of the program, following the usual rules of variable scope of the language like any other object, and using their own inheritance and transclusion rules. In the context of AngularJS, sometimes the term "$scope" (with a dollar sign) is used to oid confusion, but using the dollar sign in variable names is often discouraged by the style guides.[5]

Use[edit]

Scope is an important component of name resolution,[d] which is in turn fundamental to language semantics. Name resolution (including scope) varies between programming languages, and within a programming language, varies by type of entity; the rules for scope are called scope rules (or scoping rules). Together with namespaces, scope rules are crucial in modular programming, so a change in one part of the program does not break an unrelated part.

Overview[edit] See also: Variable (computer science) § Scope and extent

When discussing scope, there are three basic concepts: scope, extent, and context. "Scope" and "context" in particular are frequently confused: scope is a property of a name binding, while context is a property of a part of a program, that is either a portion of source code (lexical context or static context) or a portion of run time (execution context, runtime context, calling context or dynamic context). Execution context consists of lexical context (at the current execution point) plus additional runtime state such as the call stack.[e] Strictly speaking, during execution a program enters and exits various name bindings' scopes, and at a point in execution name bindings are "in context" or "not in context", hence name bindings "come into context" or "go out of context" as the program execution enters or exits the scope.[f] However, in practice usage is much looser.

Scope is a source-code level concept, and a property of name bindings, particularly variable or function name bindings—names in the source code are references to entities in the program—and is part of the behior of a compiler or interpreter of a language. As such, issues of scope are similar to pointers, which are a type of reference used in programs more generally. Using the value of a variable when the name is in context but the variable is uninitialized is analogous to dereferencing (accessing the value of) a wild pointer, as it is undefined. However, as variables are not destroyed until they go out of context, the analog of a dangling pointer does not exist.

For entities such as variables, scope is a subset of lifetime (also known as extent)—a name can only refer to a variable that exists (possibly with undefined value), but variables that exist are not necessarily visible: a variable may exist but be inaccessible (the value is stored but not referred to within a given context), or accessible but not via the given name, in which case it is not in context (the program is "out of the scope of the name"). In other cases "lifetime" is irrelevant—a label (named position in the source code) has lifetime identical with the program (for statically compiled languages), but may be in context or not at a given point in the program, and likewise for static variables—a static global variable is in context for the entire program, while a static local variable is only in context within a function or other local context, but both he lifetime of the entire run of the program.

Determining which entity a name refers to is known as name resolution or name binding (particularly in object-oriented programming), and varies between languages. Given a name, the language (properly, the compiler or interpreter) checks all entities that are in context for matches; in case of ambiguity (two entities with the same name, such as a global and local variable with the same name), the name resolution rules are used to distinguish them. Most frequently, name resolution relies on an "inner-to-outer context" rule, such as the Python LEGB (Local, Enclosing, Global, Built-in) rule: names implicitly resolve to the narrowest relevant context. In some cases name resolution can be explicitly specified, such as by the global and nonlocal keywords in Python; in other cases the default rules cannot be overridden.

When two identical names are in context at the same time, referring to different entities, one says that name masking is occurring, where the higher-priority name (usually innermost) is "masking" the lower-priority name. At the level of variables, this is known as variable shadowing. Due to the potential for logic errors from masking, some languages disallow or discourage masking, raising an error or warning at compile time or run time.

Various programming languages he various different scope rules for different kinds of declarations and names. Such scope rules he a large effect on language semantics and, consequently, on the behior and correctness of programs. In languages like C++, accessing an unbound variable does not he well-defined semantics and may result in undefined behior, similar to referring to a dangling pointer; and declarations or names used outside their scope will generate syntax errors.

Scopes are frequently tied to other language constructs and determined implicitly, but many languages also offer constructs specifically for controlling scope.

Levels of scope[edit]

Scope can vary from as little as a single expression to as much as the entire program, with many possible gradations in between. The simplest scope rule is global scope—all entities are visible throughout the entire program. The most basic modular scope rule is two-level scope, with a global scope anywhere in the program, and local scope within a function. More sophisticated modular programming allows a separate module scope, where names are visible within the module (private to the module) but not visible outside it. Within a function, some languages, such as C, allow block scope to restrict scope to a subset of a function; others, notably functional languages, allow expression scope, to restrict scope to a single expression. Other scopes include file scope (notably in C) which behes similarly to module scope, and block scope outside of functions (notably in Perl).

A subtle issue is exactly when a scope begins and ends. In some languages, such as C, a name's scope begins at the name declaration, and thus different names declared within a given block can he different scopes. This requires declaring functions before use, though not necessarily defining them, and requires forward declaration in some cases, notably for mutual recursion. In other languages, such as Python, a name's scope begins at the start of the relevant block where the name is declared (such as the start of a function), regardless of where it is defined, so all names within a given block he the same scope. In JaScript, the scope of a name declared with let or const begins at the name declaration, and the scope of a name declared with var begins at the start of the function where the name is declared, which is known as variable hoisting. Behior of names in context that he undefined value differs: in Python use of undefined names yields a runtime error, while in JaScript undefined names declared with var are usable throughout the function because they are implicitly bound to the value undefined.

Expression scope[edit]

The scope of a name binding is an expression, which is known as expression scope. Expression scope is ailable 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 oid 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) he expression scope.

In C, variable names in a function prototype he 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.

Block scope[edit]

The scope of a name binding is a block, which is known as block scope. Block scope is ailable in many, but not all, block-structured programming languages. This began with ALGOL 60, where "[e]very declaration ... is valid only for that block.",[6] and today is particularly associated with languages in the Pascal and C families and traditions. Most often this block is contained within a function, thus restricting the scope to a part of a function, but in some cases, such as Perl, the block may not be within a function.

unsigned int sum_of_squares(const unsigned int m) { unsigned int result = 0; for (unsigned int n = 1; n Learning the Ja Language > Classes and Objects)". docs.oracle.com. Retrieved 19 March 2018. ^ "Controlling Access to Members of a Class (The Ja Tutorials > Learning the Ja Language > Classes and Objects)". docs.oracle.com. Retrieved 19 March 2018. ^ "Everything you need to know about Jascript variable scope", Saurab Parakh, Coding is Cool, 2010-02-08 ^ "Annotated ES5". es5.github.io. Retrieved 19 March 2018. ^ "Functions". MDN Web Docs. Retrieved 19 March 2018. ^ "12.2 Variable Statement", Annotated ECMAScript 5.1, Last updated: 2012-05-28 ^ "JaScript Scoping and Hoisting", Ben Cherry, Adequately Good, 2010-02-08 ^ Jascript Closures, Richard Cornford. March 2004 ^ "Explaining JaScript Scope And Closures", Robert Nyman, October 9, 2008 ^ Pitman, Kent (December 16, 2007). "The Revised Maclisp Manual (The Pitmanual), Sunday Morning Edition". MACLISP.info. HyperMeta Inc. Declarations and the Compiler, Concept "Variables". Retrieved October 20, 2018. If the variable to be bound has been declared to be special, the binding is compiled as code to imitate the way the interpreter binds variables ^ Pitman, Kent (December 16, 2007). "The Revised Maclisp Manual (The Pitmanual), Sunday Morning Edition". MACLISP.info. HyperMeta Inc. The Evaluator, Special Form *FUNCTION. Retrieved October 20, 2018. *FUNCTION is intended to help solve the "funarg problem," however it only works in some easy cases. ^ Pitman, Kent; et al. (webbed version of ANSI standard X3.226-1994) (1996). "Common Lisp HyperSpec". Lispworks.com. LispWorks Ltd. 1.1.2 History. Retrieved October 20, 2018. MacLisp improved on the Lisp 1.5 notion of special variables ... The primary influences on Common Lisp were Lisp Machine Lisp, MacLisp, NIL, S-1 Lisp, Spice Lisp, and Scheme. ^ "Programming Language ISLISP, ISLISP Working Draft 23.0" (PDF). ISLISP.info. 11.1 The lexical principle. Retrieved October 20, 2018. Dynamic bindings are established and accessed by a separate mechanism (i.e., defdynamic, dynamic-let, and dynamic). ^ "Lexical Binding". EmacsWiki. Retrieved October 20, 2018. Emacs 24 has optional lexical binding, which can be enabled on a per-buffer basis. ^ "R FAQ". cran.r-project.org. Retrieved 19 March 2018. Abelson, Harold; Sussman, Gerald Jay; Sussman, Julie (1996) [1984]. Structure and Interpretation of Computer Programs. Cambridge, MA: MIT Press. ISBN 0-262-51087-1. "Lexical addressing" Scott, Michael L. (2009) [2000]. Programming Language Pragmatics (Third ed.). Morgan Kaufmann Publishers. ISBN 978-0-12-374514-9. Chapter 3: Names, Scopes, and Bindings, pp. 111–174 Section 13.4.1: Scripting Languages: Innovative Features: Names and Scopes, pp. 691–699

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至lsinopec@gmail.com举报,一经查实,本站将立刻删除。

上一篇 没有了

下一篇没有了