2019-11-24

Unsigned Integers Are Dangerous

Unsigned integers are dangerous for at least two reasons:
  • Danger1: "unsigned integers are highly infectious and possibly lethal to desired arithmetic."  Unsigned integers can transform your nice signed integer math into unexpected and unwanted unsigned integer math.  Ex: the unsignedness of 1u infects the C/C++ expression -1/1u so that it yields a large unsigned integer which may go on to infect more arithmetic.
  • Danger2: "unsigned integers almost always teeter on the cliff-edge of underflow, sometimes falling and killing desired behavior."  Underflow and overflow of integers often lead to unwanted behavior, and unsigned integers often hold small values that could easily underflow after common operations like i-- or i-1.  Signed integers often hold small values that are very far away from both underflow and overflow.
Danger1 depends on how your language treats operations with mixed signedness.  C and C++ (and probably many more languages) do have the dangerous behavior of preferring to generate unsigned integers.  Danger2 is for basically all languages.

Due to the severity and generality of these dangers, I recommend the mindset of "use signed integers unless you must use an unsigned integer for a specific reason".  Some acceptable situations to use unsigned integer variables...
  • If you have some variable/constant that will only by touched by bit-wise operations and not arithmetic.
  • If you really need to be stingy with your variable sizes and need the extra positive range of unsigned integers.