Function scope (computer science)

From Wiki @ Karl Jones dot com
Revision as of 07:11, 26 August 2016 by Karl Jones (Talk | contribs) (Created page with "In computer science, '''function scope''' is the scope of functions. == Description == Most of the commonly used Programmin...")

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

In computer science, function scope is the scope of functions.

Description

Most of the commonly used programming languages offer a way to create a local variable in a function or subroutine: a variable whose scope ends (that goes out of context) when the function returns.

In most cases the lifetime of the variable is the duration of the function call – it is an automatic variable, created when the function starts (or the variable is declared), destroyed when the function returns – while the scope of the variable is within the function, though the meaning of "within" depends on whether scoping is lexical or dynamic.

However, some languages, such as C, also provide for static local variables, where the lifetime of the variable is the entire lifetime of the program, but the variable is only in context when inside the function.

In the case of static local variables, the variable is created when the program initializes, and destroyed only when the program terminates, as with a static global variable, but is only in context within a function, like an automatic local variable.

Importantly, in lexical scoping a variable with function scope has scope only within the lexical context of the function: it moves out of context when another function is called within the function, and moves back into context when the function returns – called functions have no access to the local variables of calling functions, and local variables are only in context within the body of the function in which they are declared.

By contrast, in dynamic scoping, the scope extends to the runtime context of the function: local variables stay in context when another function is called, only moving out of context when the defining function ends, and thus local variables are in context of the function in which they are defined and all called functions.

In languages with lexical scoping and nested functions, local variables are in context for nested functions, since these are within the same lexical context, but not for other functions that are not lexically nested. A local variable of an enclosing function is known as a non-local variable for the nested function.

Function scope is also applicable to anonymous functions.

See also

External links