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;
}
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.