← Back to context

Comment by charlie90

21 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.

> 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.

  • In C your compiler can help you with conversions and if not, please use a better one. In this regard, C is a very pragmatic language, and hence for actual work it is a more "serious" programming language than programming languages which are based on some idealistic theory that pedantic typing will fix all your problems, but actually keep you from doing your job.

    • Sentence 1: The C compiler can help you catch implicit conversion errors.

      Sentence 2: Catching implicit conversion errors is idealistic, pedantic, and prevents you from doing your job.

      Great stuff. 10/10. No notes.

      1 reply →