6.15 Unary Scope Resolution Operator

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.

Fig. 6.19 Unary scope resolution operator.

Alternate View

 1   // Fig. 6.19: fig06_19.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      double number{10.5}; // local variable named number 
10
11      // display values of local and global variables
12      cout << "Local double value of number = " << number
13         << "
Global int value of number = " << ::number << endl;
14   }

Local double value of number = 10.5
Global int value of number = 7

Good Programming Practice 6.5

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.

 

Software Engineering Observation 6.10

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.10

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.11

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset