C++ provides the unary scope resolution operator (::
) to access a global variable when a local variable of the same name is in scope.5 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.19 shows the unary scope resolution operator with local and global variables of the same name (lines 6 and 9). To emphasize that the local and global versions of variable number
are distinct, the program declares one variable int
and the other double
.
Always using the unary scope resolution operator (::
) to refer to global variables (even if there is no collision with a local-variable name) makes it clear that you’re intending to access a global variable rather than a local variable.
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.
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.