Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Home » Tip Bank » C++
Language: C++
Expertise: All
Jun 4, 1998

Be cautious with unsigned integers

Unsigned integers are sometimes unavoidable, like when dealing with raw binary data. A good example is a mail server reading an incoming binary stream. But more often than not, the unsigned specifier is better avoided, since it can be quite dangerous:

1. Unsigned may limit future extensions and can cause nasty bugs:

 	
	typedef unsigned int zip;
	zip translate(string& cityname); //compute mail zip
The function above retrieves a city code from a lookup table by its name. For new cities, which don't have a code in the lookup table yet, 0 is returned. That seems quite straightforward. Nevertheless, future maintainers of this function may discover a problem: how to handle a validation exception such as empty/corrupted string? Had the function been declared as returning signed int, a negative number to signal such an exception could have been applied. In other words, unsigned can limit possible future extensions.

2. Negative numbers can be converted to unsigned implicitly, with unexpected results:

 
	void translate(unsigned int); //code to text

	const int MEM_EXCEPTION_CODE = -100;

void main() 
{	//...many lines of code; an exception has occurred

 	translate(MEM_EXCEPTION_CODE); //signed to unsigned implicit
	//conversion; probably disastrous
}

So unless you are packing binary datagrams to be transmitted via a communication link, using a signed integral type is usually a more portable, safe, and robust choice.
Danny Kalev
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date