watashiSHUN
watashiSHUN

Reputation: 10504

what are the extra works Java compiler need to implement block scope?

function scope makes sense to me since a local variable's lifetime == it's visibility, but I am a little uncertain about block scope

looking at this java code:

public static void main(String[] args) {
    int j;
    { // block A
        int i;
    }
    { // block B
        int i;
    }
}
  1. When the function is called, all three variables have their space allocated on call stack? Even though i is not accessible outside of the block, it is not removed until function returns? (If it is removed after block terminates, how to implement this? if imitating call stack, we lose access to j...)
  2. if 1 is true, while compiling, Java needs to give a namespace to each scope before putting them in the symbol table? (something like blockA.i = sp+4, blockB.i = sp+8). if 1 is false, I guess it just solved the name conflict issue
  3. int j;{int j;} is not allowed in Java, does the compiler also needs to check if there's a conflict (before the rename) in the current symbol table? (I know this is allowed in C++)

Upvotes: 1

Views: 70

Answers (1)

dabaicai
dabaicai

Reputation: 999

Let's change your code like following:

public static void main(String[] args) {
    int j;
    { // block A
        int i;
        i=1;
    }
    { // block B
        int i;
        i=1;
    }
}

And see the byte code of above code after compile.

public static void main(java.lang.String[]);
descriptor: ([Ljava/lang/String;)V
flags: ACC_PUBLIC, ACC_STATIC
Code:
  stack=1, locals=3, args_size=1
     0: iconst_1
     1: istore_2     //statement 1
     2: iconst_1
     3: istore_2     //statement 2
     4: return
  LineNumberTable:
    line 14: 0
    line 18: 2
    line 20: 4
  LocalVariableTable:
    Start  Length  Slot  Name   Signature
        0       5     0  args   [Ljava/lang/String;

Look at the statement 1 and statement 2,that means the local variable i in different scope is save same location that is stored at slot 2 at local variable table.

And because of variable i is in different scope,when the program execute at block two,the local variable i in block one is invalid,so we can use that slot of the local variable i.

The java compiler also check the if there be same identifier at current scope.Note the current scope means that you can declare variables that has same name in instance scope and local scope respectively,but not all in instance scope or local scope.

Upvotes: 1

Related Questions