It’s possible to declare local and global variables of the same name. C++ provides the unary scope resolution operator (::) to access a global variable when a local variable of the same name is in scope. The unary scope resolution operator cannot be used to access a local variable of the same name in an outer block. A global variable can be accessed directly without the unary scope resolution operator if the name of the global variable is not the same as that of a local variable in scope.
Figure 6.21 shows the unary scope resolution operator with local and global variables of the same name (lines 6 and 10). To emphasize that the local and global versions of variable number
are distinct, the program declares one variable int
and the other double
.
1 // Fig. 6.21: fig06_21.cpp
2 // Unary scope resolution operator.
3 #include <iostream>
4 using namespace std;
5
6 int number = 7; // global variable named number
7
8 int main()
9 {
10 double number = 10.5; // local variable named number
11
12 // display values of local and global variables
13 cout << "Local double value of number = " << number
14 << "
Global int value of number = " << ::number << endl;
15 } // end main
Local double value of number = 10.5
Global int value of number = 7
Good Programming Practice 6.6
Always using the unary scope resolution operator (::) to refer to global variables makes it clear that you’re intending to access a global variable rather than a nonglobal variable.
Software Engineering Observation 6.11
Always using the unary scope resolution operator (::) to refer to global variables makes programs easier to modify by reducing the risk of name collisions with nonglobal variables.
Always using the unary scope resolution operator (::) to refer to a global variable eliminates logic errors that might occur if a nonglobal variable hides the global variable.
Error-Prevention Tip 6.8
Avoid using variables of the same name for different purposes in a program. Although this is allowed in various circumstances, it can lead to errors.