The Scope Resolution Operator

In C, a local variable takes precedence over a global variable with the same name. For example, if both a local variable and a global variable are called count, all occurrences of count while the local variable is in scope refer to the local variable. It's as if the global variable becomes invisible.

In C++, you can tell the compiler to use the global variable rather than the local one by prefixing the variable with ::, the scope resolution operator. For example:

// Scope resolution operator

#include <iostream.h>

int amount = 123; // A global variable

void main()

{

int amount = 456; // A local variable

cout << ::amount; // Print the global variable

cout << '\n';

cout << amount; // Print the local variable

}

The example has two variables named amount. The first is global and contains the value 123. The second is local to the main function. The two colons tell the compiler to use the global amount instead of the local one. The program prints this on the screen:

123

456

Note that if you have nested local scopes, the scope resolution operator doesn't provide access to variables in the next outermost scope. It provides access to only the global variables.

The scope resolution operator gives you more freedom in naming your variables by letting you distinguish between variables with the same name. However, you shouldn't overuse this feature; if two variables have different purposes, their names should reflect that difference.