Posted on Leave a comment

Block Scope for Local Variables – Access Control

Block Scope for Local Variables

Declarations and statements can be grouped into a block using curly brackets, {}. Blocks can be nested, and scope rules apply to local variable declarations in such blocks. A local declaration can appear anywhere in a block. The general rule is that a variable declared in a block is in scope in the block in which it is declared, but it is not accessible outside this block. It is not possible to redeclare a variable if a local variable of the same name is already declared in the current scope.

Local variables of a method include the formal parameters of the method and variables that are declared in the method body. The local variables in a method are created each time the method is invoked, and are therefore distinct from local variables in other invocations of the same method that might be executing (§7.1, p. 365).

Figure 6.6 illustrates block scope (also known as lexical scope) for local variables. It shows four blocks: Block 1 is the body of the method main(), Block 2 is the body of the for(;;) loop, Block 3 is the body of a switch statement, and Block 4 is the body of an if statement.

  • Parameters cannot be redeclared in the method body, as shown at (1) in Block 1.
  • A local variable—already declared in an enclosing block, and therefore visible in a nested block—cannot be redeclared in the nested block. These cases are shown at (3), (5), and (6).
  • A local variable in a block can be redeclared in another block if the blocks are disjoint—that is, they do not overlap. This is the case for variable i at (2) in Block 3 and at (4) in Block 4, as these two blocks are disjoint.

The scope of a local variable declaration begins from where it is declared in the block and ends where this block terminates. The scope of the loop variable index is the entire Block 2. Even though Block 2 is nested in Block 1, the declaration of the variable index at (7) in Block 1 is valid. The scope of the variable index at (7) spans from its declaration to the end of Block 1, and it does not overlap with that of the loop variable index in Block 2.

  

Figure 6.6 Block Scope

Leave a Reply

Your email address will not be published. Required fields are marked *