Scope
- This article is not detailed enough and needs to be expanded. Please help us by adding some more information.
Scope is a limitation placed on where a variable can be used, so that what value a name refers to is never ambiguous. If a programmer defines the variable value-to-be-returned
inside a function, then writes an almost identical function for a similar purpose, scope allows her to call the corresponding variable in the second function value-to-be-returned
as well. Restrictions on scope mean that variables from within one function can never inadvertently leak values to another function, no matter the names used. There is no consensus on the perfect way to manage scope, although certain systems are common in programming languages.
Philosophically, scope is interrelated with modularity and separation of concerns. That is, it is easiest to reason about programs that can be broken down into discrete parts, and careful scope rules can minimise unwanted interaction between those separate parts.
Global scope
The simplest scoping rule is global scope, which means that a variable can be read and written to by any part of the program, or in more extreme cases, the whole computer system. If the programmer sets foo
equal to three, then the whole program will see that it is three. Many languages provide facilities to refer global variables in addition to other scoping rules. In general, misuse of global variables is thought to make bugs harder to find, because it is easy to forget to overwrite a saved value from elsewhere in a program. Ideally, (some would say) changing one part of a program should only affect that part of the program.
Local scope
A prevalent scoping rule is that variables that are defined within a function should only be available within that particular function. This is especially essential in functional programming in order to avoid side-effects from having one function affect another.
Dynamic scope vs. Lexical scope
Languages with scoping rules often divide into two camps: lexical scope, or dynamic scope. While it is generally agreed that local variables should stay inside their respective functions, it can be unclear what is and isn't inside a function. For instance, should a function called from inside another function be able to use variables from the caller? Lexically scoped languages have it that a local variable should be usable from explicit references to it from within the function itself's source code, and nowhere else. Dynamic scope tends to prefer a different system: if a variable is not found within a function, check in its caller, and if not found, in the caller's caller, and so on until the global scope is reached.