6.16. 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.
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
Good Programming Practice 6.7
Software Engineering Observation 6.17
Error-Prevention Tip 6.4
Error-Prevention Tip 6.5