Unary Scope Resolution Operator
It is 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.23 demonstrates the unary scope resolution operator with local and global variables of the same name (lines 7 and 11). To emphasize that the local and global versions of variable number are distinct, the program declares one variable of type int and the other double.
Figure 6.23. Unary scope resolution operator.
1 // Fig. 6.23: fig06_23.cpp 2 // Using the unary scope resolution operator. 3 #include 4 using std::cout; 5 using std::endl; 6 7 int number = 7; // global variable named number 8 9 int main() 10 { 11 double number = 10.5; // local variable named number 12 13 // display values of local and global variables 14 cout << "Local double value of number = " << number 15 << " Global int value of number = " << ::number << endl; 16 return 0; // indicates successful termination 17 } // end main
|
Using the unary scope resolution operator (::) with a given variable name is optional when the only variable with that name is a global variable.
Common Programming Error 6.20
It is an error to attempt to use the unary scope resolution operator (::) to access a nonglobal variable in an outer block. If no global variable with that name exists, a compilation error occurs. If a global variable with that name exists, this is a logic error, because the program will refer to the global variable when you intended to access the nonglobal variable in the outer block. |
Good Programming Practice 6.7
Always using the unary scope resolution operator (::) to refer to global variables makes programs easier to read and understand, because it makes it clear that you are intending to access a global variable rather than a nonglobal variable. |
Software Engineering Observation 6.17
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. |
Error-Prevention Tip 6.4
Always using the unary scope resolution operator (::) to refer to a global variable eliminates possible logic errors that might occur if a nonglobal variable hides the global variable. |
Error-Prevention Tip 6.5
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. |