Consider a program that calls a swap() function.
#include <iostream.h>
void swap(int x, int y) {
int temp = x;
x = y;
y = temp;
}
int main()
{
int A, B;
cin >> A >> B;
cout << "A: " <<
A << "." << endl;
cout << "B: " <<
B << "." << endl;
swap(A, B);
cout << "A: " <<
A << "." << endl;
cout << "B: " <<
B << "." << endl;
return 0;
}
Consider variables which are in scope
(DEF: portion of a program in which a
variable is legally accessible) in
the main() and swap() functions:
|
|
|
|
|
|
If you attempted to use A was in swap(),
a compilation error would result ("undeclared identifier") since it is
a local variable in only main().
#include <iostream.h>
double w;
void Z() {
w = 0;
return;
}
void Q() {
int index;
w = 2;
return;
}
int main() {
int i;
w = 4;
return 0;
}
w is a global variable which is in scope in all three functions in this program: Z(), Q(), and main(). This program also has local variables: index is local to Q(), and i is local to main().
Scoping can viewed easily in the following
table.
|
|
|
|
|
|
|
|
int sum;
void Z(int alpha) {
sum += 1;
alpha *= 3;
return;
}
double total;
void Q() {
int index;
total = index;
return;
}
int main() {
int i;
int w = 10;
sum = 0;
total = 0;
return 0;
}
We construct the scoping table.
|
|
|
|
|
|
|
|
Note that since the variable total
is declared below Z() in the text, total is not in scope in Z().