Be cautious with unsigned integers

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:
Heading photo, Metadata.

What is Metadata?

What is metadata? Well, It’s an odd concept to wrap your head around. Metadata is essentially the secondary layer of data that tracks details about the “regular” data. The regular

XDR solutions

The Benefits of Using XDR Solutions

Cybercriminals constantly adapt their strategies, developing newer, more powerful, and intelligent ways to attack your network. Since security professionals must innovate as well, more conventional endpoint detection solutions have evolved

AI is revolutionizing fraud detection

How AI is Revolutionizing Fraud Detection

Artificial intelligence – commonly known as AI – means a form of technology with multiple uses. As a result, it has become extremely valuable to a number of businesses across

AI innovation

Companies Leading AI Innovation in 2023

Artificial intelligence (AI) has been transforming industries and revolutionizing business operations. AI’s potential to enhance efficiency and productivity has become crucial to many businesses. As we move into 2023, several