What is the difference between scope and block?

后端 未结 9 1075
旧巷少年郎
旧巷少年郎 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条回答
  • 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.
    }
    
    0 讨论(0)
  • 2021-01-04 06:06

    when it comes to conditions and loops if you don't specify {} then immediate following statement is the only statement that will belong to particular condition or loop

    e.g.

    x = 10;
    if(x ==10) 
    { 
    int y = 20; 
    x = y * 2;
    }
    both lines get executes only if condition returns TRUE
    
    x = 10;
    if(x ==10) 
    int y = 20;
    x = y * 2; // this is not belong to if condition. therefore it will execute anyway
    
    0 讨论(0)
  • 2021-01-04 06:06

    For programming languages in general, the scope of a block (also known as block scope) is just one kind of scope; see https://en.wikipedia.org/wiki/Scope_(computer_science)#Levels_of_scope.

    Some languages, like Python, do not have blocks nor block scopes (but instead have function scopes, global scopes, etc.).

    0 讨论(0)
提交回复
热议问题