What is the difference between scope and block?

后端 未结 9 1155
旧巷少年郎
旧巷少年郎 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 05:49

    Scope refers to the visibility of variables. In other words, which parts of your program can see or use it. Normally, every variable has a global scope. Once defined, every part of your program can access a variable.

    It is very useful to be able to limit a variable's scope to a single function/block. The variable will have a limited scope. This way, changes inside the function/block can't affect the main program in unexpected ways.

提交回复
热议问题