What is the difference between scope and block?

后端 未结 9 1153
旧巷少年郎
旧巷少年郎 2021-01-04 05:16

I saw a piece of code in a book, which is as follows:

x = 10;
if(x ==10) { // start new scope
int y = 20; // known only to this block
x = y * 2;
}

9条回答
  •  旧时难觅i
    2021-01-04 06:04

    They are mostly the same.

    A block is some code surrounded by { and }. A scope is the part of the program where a certain thing is visible. As far as I know, all blocks create scopes - anything defined in a block isn't visible outside the block. The converse is not true.

    Here are some scopes without blocks:

    for(int k = 0; k < 10; k++) { // k<10 and k++ are in a scope that includes k, but not in a block.
        System.out.println(k); // this is in a block (the {})
    }
    
    for(int k = 0; k < 10; k++) // k<10 and k++ are in a scope that includes k, as above
        System.out.println(k); // but there's no block!
    
    class Test {
        // this is a scope but not a block. Not entirely sure about this one.
        int x = 2;
        int y = x + 1; // I can access x here, but not outside the class, so the class must be a scope.
    }
    

提交回复
热议问题