Roping in a scope
A variable lives in a scope. A scope defines an area, for example, the body of a function where variables exist. A lexical scope (also known as static scope) defines how variable names are resolved in nested functions. Inner functions contain the scope of enclosing (parent) functions.
Variables defined in the parent functions are available to the inner functions. Variables have the habit of coming in and going out of a scope.
For example, consider the following Java code snippet:
… int v = 9; … for (int v = 0; v < 10; ++v) { // compilation error // Do something }
The compiler will flag an error, as there is already another variable v
in the scope.
Why does the following, slightly weird, Java code compile though? Let's check:
int k = 0; { int i = 1; // 1 k += i; } { int i = 1; // 2 k += i; } System.out.println(k);
It compiles fine because blocks introduce a scope...