Casey
Casey

Reputation: 10976

Is it a best practice to use unsigned data types to enforce non-negative and/or valid values?

Recently, during a refactoring session, I was looking over some code I wrote and noticed several things:

  1. I had functions that used unsigned char to enforce values in the interval [0-255].
  2. Other functions used int or long data types with if statements inside the functions to silently clamp the values to valid ranges.
  3. Values contained in classes and/or declared as arguments to functions that had an unknown upper bound but a known and definite non-negative lower bound were declared as an unsigned data type (int or long depending on the possibility that the upper bound went above 4,000,000,000).

The inconsistency is unnerving. Is this a good practice that I should continue? Should I rethink the logic and stick to using int or long with appropriate non-notifying clamping?

A note on the use of "appropriate": There are cases where I use signed data types and throw notifying exceptions when the values go out of range but these are reserved for divde by zero and constructors.

Upvotes: 5

Views: 2983

Answers (4)

John Sallay
John Sallay

Reputation: 251

I would probably argue that consistency is most important. If you pick one way and do it right then it will be easy for someone else to understand what you are doing at a later point in time. On the note of doing it right, there are several issues to think about.

First, it is common when checking if an integer variable n is in a valid range, say 0 to N to write:

if ( n > 0 && n <= N ) ...

This comparison only makes sense if n is signed. If n is unsigned then it will never be less than 0 since negative values will wrap around. You could rewrite the above if as just:

if ( n <= N ) ...

If someone isn't used to seeing this, they might be confused and think you did it wrong.

Second, I would keep in mind that there is no guarantee of type size for integers in c++. Thus, if you want something to be bounded by 255, an unsigned char may not do the trick. If the variable has a specific meaning then it may be valuable to to a typedef to show that. For example, size_t is a value as wide as a memory address. Which means that you can use it with arrays and not have to worry about being on 32 or 64 bit machines. I try to use such typedefs whenever possible because they clearly communicate why I am using the type. (size_t because I'm accessing an array.)

Third, is back on the issue of wrap around. What do you want to happen with an invalid number. In the case of an unsigned char, if you use the type to bound the data, then you won't be able to check if a value over 255 was entered. That may or may not be a problem.

Upvotes: 2

Keith Thompson
Keith Thompson

Reputation: 263637

In C and C++, signed and unsigned integer types have certain specific characteristics.

Signed types have bounds far from zero, and operations that exceed those bounds have undefined behavior (or implementation-defined in the case of conversions).

Unsigned types have a lower bound of zero and an upper bound far from zero, and operations that exceed those bounds quietly wrap around.

Often what you really want is a particular range of values with some particular behavior when operations exceed those bounds (saturation, signaling an error, etc.). Neither signed nor unsigned types are entirely suitable for such requirements. And operations that mix signed and unsigned types can be confusing; the rules for such operations are defined by the language, but they're not always obvious.

Unsigned types can be problematic because the lower bound is zero, so operations with reasonable values (nowhere near the upper bound) can behave in unexpected ways. For example, this:

for (unsigned int u = 10; u >= 0; u --) {
    // ...
}

is an infinite loop.

One approach is to use signed types for everything that doesn't absolutely require an unsigned representation, choosing a type wide enough to hold the values you need. This avoids problems with signed/unsigned mixed operations. Java, for example, enforces this approach by not having unsigned types at all. (Personally, I think that decision was overkill, but I can see the advantages of it.)

Another approach is to use unsigned types for values that logically cannot be negative, and be very careful with expressions that might underflow or that mix signed and unsigned types.

(Yet another is to define your own types with exactly the behavior you want, but that has costs.)

As John Sallay's answer says, consistency is probably more important than which particular approach you take.

I wish I could give a "this way is right, that way is wrong" answer, but there really isn't one.

Upvotes: 6

Pubby
Pubby

Reputation: 53097

The biggest benefit from unsigned is that it documents your code that the values are always positive.

It doesn't really buy you any safety as going outside the range of an unsigned is usually unintentional and can cause just as much frustration as if it were signed.

I had functions that used unsigned char to enforce values in the interval [0-255].

If you're relying on the wraparound then use uint8_t as unsigned char could possibly be more than 8 bits.

Other functions used int or long data types with if statements inside the functions to silently clamp the values to valid ranges.

Is this really the correct behavior?

Values contained in classes and/or declared as arguments to functions that had an unknown upper bound but a known and definite non-negative lower bound were declared as an unsigned data type (int or long depending on the possibility that the upper bound went above 4,000,000,000).

Where did you get an upper bound of 4,000,000,000 from? Your bound is between INT_MAX and INT_MIN (you can also use std::numeric_limits. In C++11 you can use decltype to specify the type which you can wrap into a template/macro:

decltype(4000000000) x; // x can hold at least 4000000000

Upvotes: 2

111111
111111

Reputation: 16168

This is a subjective issue but I'll give you my take.

Personally if there isn't type designated to the operation I am trying to carray out, IE std::size_t for sizes and index, uintXX_t for specific bit depths etc... then I default to unsigned unless I need to use negative values.

So it isn't a case of using it to enforce positive values, but rather I have to select signed feature explicitly.

As well as this I if you are worried about boundaries then you need to do your own bounds checking to ensure that you aren't overflowing.

But I said, more often then not your datatype will be decided by your context with the return type of the functions you apply it to.

Upvotes: 0

Related Questions