| ▲ | throwaway894345 13 hours ago | ||||||||||||||||||||||
Why does an unsigned type for sizes or indices fare worse than a signed type? When do I want the -247th element in an array? When do I have a block that is -10 bytes in size? | |||||||||||||||||||||||
| ▲ | charlie90 11 hours ago | parent | next [-] | ||||||||||||||||||||||
Because doing subtraction on sizes/indicies is common, and signed handles the case where you subtract below 0. Unsigned yields unintuitive results. i.e, unsigned fails silently. For example, looping to the 2nd to last item in an array or getting the index before the given index. The source of confusion is that unsigned is a terrible name. Unsigned does not mean non-negative. Its 100% complete valid to assign a negative value to an unsigned, it just fails silently. If you want non-negative integers, then you should make a wrapper class that enforces non-negativity at compile and runtime. | |||||||||||||||||||||||
| |||||||||||||||||||||||
| ▲ | uecker 13 hours ago | parent | prev | next [-] | ||||||||||||||||||||||
the reason is not that you want a negative index or size, but that you want the computation of the index to be correct, and you want to have obvious errors. Both turns out to be easier with signed types. | |||||||||||||||||||||||
| ▲ | kevin_thibedeau 13 hours ago | parent | prev | next [-] | ||||||||||||||||||||||
There are (rare) times when you want negative array indices. C lets you index in both directions from a pointer to the middle of an array. That's why array indexing is signed in C. Some libc ctypes lookup tables do this. For sizing there is no strong case for negatives other than to shoehorn them into signed operations. | |||||||||||||||||||||||
| |||||||||||||||||||||||
| ▲ | wavemode 12 hours ago | parent | prev [-] | ||||||||||||||||||||||
> When do I want the -247th element in an array? You never want any element of an array, except elements within the range [0, array_length). Anything outside of that is undefined behavior. I think people tend to overthink this. A function which takes an index argument, should simply return a result when the index is within the valid range, and error if it's outside of it (regardless of whether it's outside by being too low or too high). It doesn't particularly matter that the integer is signed. If you aren't storing 2^64 elements in your array (which you probably aren't - most systems don't even support addressing that much memory) then the only thing unsigned gets you is a bunch of footguns (like those described in the OP article). | |||||||||||||||||||||||