11 ms·
For me, the main reason to prefer unsigned integers whenever possible is: less special cases. When a signed integer is used as an array index, the value can be
by cesarb 5y ago
For me, the main reason to prefer unsigned integers whenever possible is: less special cases.
When a signed integer is used as an array index, the value can be in one of three ranges: the <0 range, the >=0 && <size range, and the >=size range. To validate the index, you need two comparisons. When an unsigned integer is used as an array index, there are only two ranges: the <size range, and the >=size range, and you need only a single comparison.
And that's not the worst situation with signed integers. From a more general point of view, there are four "classes" of signed integer: positive (>0), zero, negative (<0), and INT_MIN. Everybody tends to forget about that last one, but it's "special" in that it can break things in unexpected ways. Negating it doesn't work (you'd expect negating any number less than zero to result in a number greater than zero, but for INT_MIN that doesn't happen). Dividing it can trap (see for instance https://kqueue.org/blog/2012/12/31/idiv-dos/ https://kqueue.org/blog/2012/12/31/idiv-dos/ which has a couple of examples) or worse.
With unsigned integers, there are only two "classes", zero and non-zero, and it's common to not even need special treatment for zero, reducing the whole thing to a single "class" of values.
- phkahler 5y ago>> To validate the index, you need two comparisons. If your code doesn't have bugs, no validation of indexes is required.
- cesarb 5y ago> If your code doesn't have bugs, no validation of indexes is required. Your code doesn't have bugs because you validated your indexes. What you said makes some sense when the index comes from within the program itself, but not when it comes from outside the program. Consider for instance the case of reading a data structure from a file or the network, where one field is an index or an offset into another part of the structure; you must validate that this index or offset is not outside the bounds, no matter how perfect your code is.
- kingcharles 5y agoThe number of programs ever written without bugs can be counted in a uint8.