Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Scope (computer science)
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
=== Block scope === The scope of a name binding is a [[Block (programming)|block]], which is known as '''block scope'''. Block scope is available in many, but not all, block-structured programming languages. This began with [[ALGOL 60]], where "[e]very declaration ... is valid only for that block.",<ref>{{Cite journal|last2=Wegstein|first2=J. H.|last3=Van Wijngaarden|first3=A.|last4=Woodger|first4=M.|last5=Bauer|first5=F. L.|last6=Green|first6=J.|last7=Katz|first7=C.|last8=McCarthy|first8=J.|last9=Perlis|first9=A. J.|year=1960|title=Report on the algorithmic language ALGOL 60|journal=Communications of the ACM|volume=3|issue=5|page=299|doi=10.1145/367236.367262|last1=Backus|first1=J. W.|last10=Rutishauser|first10=H.|last11=Samelson|first11=K.|last12=Vauquois|first12=B.|s2cid=278290|doi-access=free}}</ref> and today is particularly associated with languages in the [[Pascal (programming language)|Pascal]] and [[C (programming language)|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. <syntaxhighlight lang="C"> unsigned int sum_of_squares(const unsigned int N) { unsigned int ret = 0; for (unsigned int n = 1; n <= N; n++) { const unsigned int n_squared = n * n; ret += n_squared; } return ret; } </syntaxhighlight> 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 <var>n</var>, which is initialized once and incremented on each iteration of the loop, and the auxiliary variable <var>n_squared</var>, 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 <var>i</var> has accidentally already been set to another value. In this example the expression <code>n * n</code> would generally not be assigned to an auxiliary variable, and the body of the loop would simply be written <code>ret += n * n</code> 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 loop]]s, 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 <var>n</var>, 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 <var>n</var> would result in a syntax error, and one of the <var>n</var> 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: <syntaxhighlight lang="python"> if c: a = "foo" else: a = "" </syntaxhighlight> where <code>a</code> is accessible after the <code>if</code> statement. In Perl, which has block scope, this instead requires declaring the variable prior to the block: <syntaxhighlight lang="perl"> my $a; if (c) { $a = 'foo'; } else { $a = ''; } </syntaxhighlight> 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: <syntaxhighlight lang="python"> a = "" if c: a = "foo" </syntaxhighlight> while in Perl this would be: <syntaxhighlight lang="perl"> my $a = ''; if (c) { $a = 'foo'; } </syntaxhighlight> 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. <syntaxhighlight lang="perl" style="float:right;margin-left:1em"> { my $counter = 0; sub increment_counter { return ++$counter; } } </syntaxhighlight> 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, <code>$counter</code> is a variable name with block scope (due to the use of the <code>my</code> keyword), while <code>increment_counter</code> is a function name with global scope. Each call to <code>increment_counter</code> will increase the value of <code>$counter</code> by one, and return the new value. Code outside of this block can call <code>increment_counter</code>, but cannot otherwise obtain or alter the value of <code>$counter</code>. This idiom allows one to define closures in Perl.
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)