The Scope of Variables
Almost every programming language has:
1. constructs for introducing a new variable x, and
2. scoping rules for determining which uses of the variable name x in the rest of the program refer to this variable.
If the same name x is used for several different variables, a programmer can resolve which variable is really meant by a particular use of the name x.
For example, in Java a loop header may introduce a new loop variable and its scope:
for (int i = 0; i < NumOfElements; i++) ... ;
The scope of the variable i is the program text following the = all the way to the end of the loop body. If the loop contains a break construct and if the loop is followed by some statement like
System.out.println("the index where we stopped searching is " + i);
then we know from the scoping rules for Java that the program is almost certainly erroneous. Since the use of i in the invocation of println does not refer to the variable i that was introduced as the loop variable, the reference to variable i in the print statement either is illegal or refers to a variable with a scope that encloses the loop and the subsequent print statement.
Note: We analyzed the preceding program fragment with a rough understanding of its execution semantics but with a precise understanding of the scoping rules. These scoping rules are crucial for building a good mental execution model.
Other examples of scoping constructs in Java and C++ include
* class definitions,
* method definitions,
* parameter declarations, and
* sequences of statements (tails of blocks)
No comments:
Post a Comment