|
In other words, which parts of your program can see or use the variable.
| Every variable NAME that is defined in the outer scope, will be visible (i.e.: known) in the inner scope |
We will learn the precise scoping rule shortly.
| And you can define an "inner inner scope" inside the inner scope, and so on (scoping levels can go on indefinitely) |
|
.....
{ (Begin of outer scope)
....
....
{ (Begin of inner scope)
(Inner scope)
....
....
} (End of inner scope)
....
....
}(Begin of outer scope)
|
int main(int argc, char *argv[])
{
int x;
x = 1; // (1) int x is accessible after its definition
cout << "x = " << x << "\n"; // prints 1
{
x = 3.14; // Uses variable x at (1)
cout << "x = " << x << "\n"; // prints 3
}
cout << "x = " << x << "\n"; // prints 3
}
|
Java shows a similar behavior
int main(int argc, char *argv[])
{
int x;
x = 1; // (1) int x is accessible after its definition
cout << "x = " << x << "\n"; // prints 1
{
x = 9999; // Uses x at (1)
cout << "x = " << x << "\n"; // prints 9999
float x; // (2) <----- variable with SAME name !!
x = 3.14; // Uses x at (2) !!!
cout << "x = " << x << "\n"; // prints 3.14
}
cout << "x = " << x << "\n"; // prints 9999 !!!
// (x at (1) is unchanged by x=3.14 !)
}
|
Note that there are two different variables x in the inner scope:
int x; // defined at line (1)
float x; // defined at line (2)
|
(Java disallows this construct !!!)
|
int main(int argc, char *argv[])
{
{
int x; <--------------
x = 3; // No error
cout << "x = " << x << "\n"; // No error
}
x = 1111; // x undefined !
cout << "x = " << x << "\n"; // x undefined...
}
|
Java has the same scoping effect
 
 
 
|
Local variables:
|
Parameter variables:: behaves like local variables defined at the beginning of the function
|
int x;
int main(int argc, char **argv)
{
....
}
float f(float x)
{
....
}
|
{
int x;
int main(int argc, char **argv)
{
....
}
float f(float x)
{
....
}
}
|
|
|
Example:
int x; // (1)
int main(int argc, char **argv)
{
double x;
// Global variable x (at (1)) is no longer accessible...
....
}
float f(float x)
{
// Global variable x (at (1)) is accessible !
....
}
|
Java will forbid the user to define another variable with the same name in an inner scope
Java adopts a "careful" approach, and tries to prevent the programmer from "confusing oneself"...