24

Should one ever declare a variable as an unsigned int if they don't require the extra range of values? For example, when declaring the variable in a for loop, if you know it's not going to be negative, does it matter? Is one faster than the other? Is it bad to declare an unsigned int just as unsigned in C++?

To reitterate, should it be done even if the extra range is not required? I heard they should be avoided because they cause confusion (IIRC that's why Java doesn't have them).

5
  • 2
    What's the use of doing anything when not necessary?
    – Bo Persson
    Sep 1, 2012 at 8:51
  • @BoPersson: If someone asks "pizza or hamburger?", he probably isn't expecting a "yes" or "no" answer based on whether either one is "necessary". Similar situation here. :)
    – user541686
    Sep 1, 2012 at 9:13
  • 1
    I see this more as "should I eat if I'm not hungry?". But we might read the question differently.
    – Bo Persson
    Sep 1, 2012 at 9:16
  • 2
    I find it interesting that this other question is essentially a duplicate, but comes to the opposite conclusion: stackoverflow.com/questions/22587451/…
    – peterpi
    Apr 21, 2017 at 9:08
  • Another related question softwareengineering.stackexchange.com/q/97541/105228
    – Alex Che
    Nov 23, 2022 at 11:07

7 Answers 7

14

The reason to use uints is that it gives the compiler a wider variety of optimizations. For example, it may replace an instance of 'abs(x)' with 'x' if it knows that x is positive. It also opens up a variety of bitwise 'strength reductions' that only work for positive numbers. If you always mult/divide an int by a power of two, then the compiler may replace the operation with a bit shift (ie x*8 == x<<3) which tends to perform much faster. Unfortunately, this relation only holds if 'x' is positive because negative numbers are encoded in a way that precludes this. With ints, the compiler may apply this trick if it can prove that the value is always positive (or can be modified earlier in the code to be so). In the case of uints, this attribute is trivial to prove, which greatly increases the odds of it being applied.

Another example might be the equation y = 16 * x + 12. If x can be negative, then a multiply and add would be required. Yet if x is always positive, then not only can the x*16 term be replaced with x<<4, but since the term would always end with four zeros this opens up replacing the '+ 12' with a binary OR (as long as the '12' term is less than 16). The result would be y = (x<<4) | 12.

In general, the 'unsigned' qualifier gives the compiler more information about the variable, which in turn allows it to squeeze in more optimizations.

5
  • 1
    This, while unfortunately making perfect sense, is wrong. x * 8 and x << 3 are interchangable even for negative signed integers, on most systems. And the compiler knows, and will use shifts. I think you meant binary OR, by the way: (x << 4) | 12, which is also valid on most systems for signed integers.
    – user743382
    Sep 1, 2012 at 8:53
  • Just noticed the OR issue, fixed. I'm not too sure about the shift though, unless the << op is designed to handle ints. It should work for positive ints (as long as you don't overflow), but I reckon that negatives should fail. For example, -72 in a signed byte is "10111000". If you were to shift it right by 3 bits (eg /8), you get "00010111" which is +23, not the -9 (11110111) you want.
    – Ghost2
    Sep 1, 2012 at 23:17
  • 1
    That's about right shifts, where the sign bit needs to be preserved when you want to use it to divide. x86 assembly has the sar (shift arithmetic right) instruction for that, which behaves differently from the shr (shift right) instruction. That issue does not exist for left shifts. Besides, rounding complicates matters for divisions, but rounding issues don't exist for multiplications / left shifts either.
    – user743382
    Sep 2, 2012 at 17:18
  • "The reason" - as though there's a single reason? No. -1.
    – einpoklum
    May 12, 2019 at 20:04
  • The primary concern of a programmer should be correct code, optimizations should only be pursued if determined necessary. Use of unsigned can introduce unintended errors.
    – Glen Yates
    Aug 17, 2021 at 19:54
12

You should use unsigned integers when it doesn't make sense for them to have negative values. This is completely independent of the range issue. So yes, you should use unsigned integer types even if the extra range is not required, and no, you shouldn't use unsigned ints (or anything else) if not necessary, but you need to revise your definition of what is necessary.

17
  • 2
    @H2CO3: That's what exceptions are for. Magic values are bad.
    – Puppy
    Sep 1, 2012 at 6:52
  • 4
    "You should use unsigned integers when it doesn't make sense for them to have negative values." Why? You could just as easily make this argument "You should use signed integers if it doesn't make sense for them to have values greater than 32767." Sep 1, 2012 at 7:32
  • 2
    @BenjaminLindley: Yeah, so? The range of signed char is at least -128 to 127, and the range of long is at least -2,147,483,647 to 2,147,483,647. What does any of that have to do with "using signed integers if it doesn't make sense for them to have values greater than 32767"?
    – user541686
    Sep 1, 2012 at 9:32
  • 3
    @BenjaminLindley maybe I shouldn't have diverted the discussion to other integer types, but my point is that OP's definition of "necessary" seems to be solely related to range, whereas I think one should consider program logic first. Sep 1, 2012 at 10:26
  • 4
    @BenjaminLindely: If I have a program that counts the number of characters read, can this be negative? Can I have a negative quantity of apples? I generally use unsigned for quantities and sizes. I've never come across a negative size of a physical thing. For example, can a tree have a negative circumference? I'm letting the compiler help in defect identification or prevention. Sep 10, 2012 at 19:44
8

More often than not, you should use unsigned integers.

They are more predictable in terms of undefined behavior on overflow and such.
This is a huge subject of its own, so I won't say much more about it.
It's a very good reason to avoid signed integers unless you actually need signed values.

Also, they are easier to work with when range-checking -- you don't have to check for negative values.

Typical rules of thumb:

  • If you are writing a forward for loop with an index as the control variable, you almost always want unsigned integers. In fact, you almost always want size_t.

  • If you're writing a reverse for loop with an index as a the control variable, you should probably use signed integers, for obvious reasons. Probably ptrdiff_t would do.

The one thing to be careful with is when casting between signed and unsigned values of different sizes.
You probably want to double-check (or triple-check) to make sure the cast is working the way you expect.

15
  • 1
    "This is a huge subject of its own, so I won't say much more about it." -- Please, at least say something about it, because I have no idea what you are talking about. Sep 1, 2012 at 7:23
  • 1
    Coz a defined overflow can not cause demons to fly out of your nose. (catb.org/jargon/html/N/nasal-demons.html) Sep 1, 2012 at 7:37
  • 1
    @BenjaminLindley: It doesn't matter if you need the range for your data itself. Chances are, you don't. But what matters is whether you might need the range for your intermediate calculations. Chances are, you very well might. If he doesn't, well, then the point is moot (I didn't even see that edit when I wrote this). You might find this read interesting, though.
    – user541686
    Sep 1, 2012 at 7:38
  • 2
    @Mehrdad: If you might need larger integers, then you should use a larger integer type, not allow your integers to simply overflow. Sep 1, 2012 at 8:17
  • 1
    @Mehrdad: I read the link. It's still correct to use larger integers and incorrect to allow your integers to overflow, even if the latter works okay for some situations. Sep 1, 2012 at 8:37
8

int is the general purpose integer type. If you need an integer, and int meets your requirements (range [-32767,32767]), then use it.

If you have more specialized purposes, then you can choose something else. If you need an index into an array, then use size_t. If you need an index into a vector, then use std::vector<T>::size_type. If you need specific sizes, then pick something from <cstdint>. If you need something larger than 64 bits, then find a library like gmp.

I can't think of any good reasons to use unsigned int. At least, not directly (size_t and some of the specifically sized types from <cstdint> may be typedefs of unsigned int).

7

The problem with the systematic use of unsigned when values can't be negative isn't that Java doesn't have unsigned, it is that expressions with unsigned values, especially when mixed with signed one, give sometimes confusing results if you think about unsigned as an integer type with a shifted range. Unsigned is a modular type, not a restriction of integers to positive or zero.

Thus the traditional view is that unsigned should be used when you need a modular type or for bitwise manipulation. That view is implicit in K&R — look how int and unsigned are used —, and more explicit in TC++PL (2nd edition, p. 50):

The unsigned integer types are ideal for uses that treat storage as a bit array. Using an unsigned instead of an int to gain one more bit to represent positive integers is almost never a good idea. Attempts to ensure that some values are positive by declaring variables unsigned will typically be defeated by the implicit conversion rules.

2

In almost all architectures the cost of signed operation and unsigned operation is the same. So efficiency wise you wont get any advantage for using unsigned over signed. But as you pointed out, if you use unsigned you will have a bigger range

4
  • "If you use unsigned you'll have a bigger range" - that's only true for integers with the same length. A signed long can hold a greater value than an unsigned byte.
    – user529758
    Sep 1, 2012 at 6:55
  • 1
    @H2CO3 of course the base type should be same ( comparison is valid only between int and int, long and long, ...) Sep 1, 2012 at 6:58
  • 1
    I think you'll find the range (max-min) is exactly the same between signed and unsigned forms. (at least for twos complement forms). Sep 1, 2012 at 7:10
  • @MichaelAnderson if you mean the total number of points, yes you are right. Sep 1, 2012 at 7:12
2

Even if you have variables that should only take non negative values unsigned can be a problem. Here is an example. Suppose a programmer is asked to write a code to print all pairs of integer numbers (a,b) with 0 <= a < b <= n where n is a given input. An incorrect code is

for (unsigned b = 0; b <= n; b++)
   for (unsigned a=0; a <=b-1; b++)
       cout << a << ',' << b << n ;

This is easy to correct, but thinking with unsigned is a bit less natural than thinking with int.

1
  • I presume you mean b-1 will be UINT_MAX on the first iteration, thus something very different from intended. But the code is wrong for other reasons. Why would you think a < b but then write a <=b-1? you introduce an error by using a pointlessly cryptic expression; the former would work. And why increment b in the inner loop, instead of a? (and why use postincrement... I guess because all 2-bit tutorials still do, sadly) Nov 24, 2018 at 15:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.