Understanding the Unary Scope Resolution Operator

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.

Leave a Reply

How to post code in comments?