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.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: