Hacker News new | ask | show | jobs
by b3tta 4658 days ago
Folks... Let me ask you a related question: Why are signed integers used so (extremely) often, if the number is by definition always greater or equal to zero? Why are so few using explicit unsigned integers? Is it just a lack of understanding what the difference between signed and unsigned integers are and what happens if either one is increased/decreased over it's maximum/minimum value?
2 comments

I think most people would understand the difference if asked. There are all sorts of reasons, but no great ones:

  1) Tutorials usually use 'int' (self-referential)
  2) 'unsigned' is one more thing to type.
  3) It can be hidden behind a typedef.
  4) Negative numbers can serve as error codes.
  5) Wraparound can cause bugs for either.
  6) Occasionally safer (if x - 3 < 0)
I've usually taken to using explicit width unsigned integers (uint32_t) unless there is a reason not to.
I avoid them like a plague, except in specific situations where I need the extra range or need to save the bytes. I expect my reasons will be unpopular.

Suppose you have an object with a interface like object.setValue(7). You'd like to assert that people are sending you valid data, but if the type is uint then you can't do that. if the type is int, then you can assert(value>0, "Value must be greater than zero").

Now if anyone calls setValue(-1) you'll get an assertion that would have been skipped before.

I feel that pedants and more experienced C++ programmers will tell me I am sloppy or should be getting warnings on setValue(-1) but I've been burned before. My life is easier when I avoid unsigned types.

The behavior of int delta = unit1 - unit2 is also annoying. Not unexpected if you're paying attention, just annoying.

I might use them more if underflow / overflow caused an exception instead of undefined behavior.