| ▲ | charlie90 11 hours ago | |||||||
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. | ||||||||
| ▲ | throwaway894345 6 hours ago | parent [-] | |||||||
> 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. C’s implicit casts are tripping you up. Unsigned ints can’t be negative, but C will happily let you assign a negative signed int to an unsigned int variable, but the moment it is assigned it ceases to be negative. In serious programming languages this implicit assignment is forbidden—you have to explicitly cast. > For example, looping to the 2nd to last item in an array or getting the index before the given index. I don’t understand what you mean here, can you clarify? > If you want non-negative integers, then you should make a wrapper class that enforces non-negativity at compile and runtime. Unsigned integers are the compile time side of the coin, but yes you may want to take care to enforce it at runtime as well, though this typically implies a performance penalty that most don’t want to pay. | ||||||||
| ||||||||