The Unary Scope Resolution Operator is used to access a global variable when a local variable of the same name exists.

For example, look at the following code

#include using namespace std;

int number = 100;

int main() { double number = 27.9;

int a = number; // The global variable ::number is intended. // This line should be: int a = ::number; cout << a;
cout << number;
cout << ::number;
}
[/sourcecode]Question What is the value of A going to be? 27.9 or 100?Answer Neither, it will be 27.

Explanation One can assume that because variable a is an int and the global variable number is an int, that the global variable ::number was intended over the local variable number.

However, the local variable number that is a double was used.

Since variable a is an int, the value of the local variable number is casted to an int when assigned, so 27.9 becomes 27.

This can lead to difficult to solve bugs. The value should be 100 but is 27.

Looking at the code, this doesn’t look obviously wrong.

If a developer makes it a practice to always preface global variables with the Unary Scope Resolution Operator, such bugs can be avoided.

My other blogs

Entries (RSS) and Comments (RSS). Copyright ® Rhyous.com Linking to content on this site is allowed without permission and as many as ten lines of any article can be used along with such link. Any other use of the content is allowed only by permission of Rhyous.com.