Rhyous

September 22, 2009

Understanding the Unary Scope Resolution Operator

Filed under: Uncategorized — J. Abram barneck @ 4:01 am

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 <iostream>
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;
}

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.

Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: