Next: , Previous: , Up: Rules When Writing New C Code   [Contents][Index]


8.6 Proper Use of Unsigned Types

Avoid using unsigned int and unsigned long whenever possible. Unsigned types are viral – any arithmetic or comparisons involving mixed signed and unsigned types are automatically converted to unsigned, which is almost certainly not what you want. Many subtle and hard-to-find bugs are created by careless use of unsigned types. In general, you should almost never use an unsigned type to hold a regular quantity of any sort. The only exceptions are

  1. When there’s a reasonable possibility you will actually need all 32 or 64 bits to store the quantity.
  2. When calling existing API’s that require unsigned types. In this case, you should still do all manipulation using signed types, and do the conversion at the very threshold of the API call.
  3. In existing code that you don’t want to modify because you don’t maintain it.
  4. In bit-field structures.

Other reasonable uses of unsigned int and unsigned long are representing non-quantities – e.g. bit-oriented flags and such.