Hacker News new | ask | show | jobs
by throwaway894345 53 days ago
> 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.

1 comments

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.

The point is that you can get the warnings without having to deal with a strict type system all the time.
Warnings are just noise, so there's no point in printing them--they will be ignored (maybe not when there is a singular warning, but if warnings are allowed to accumulate beyond some manageable threshold). If a warning is worth printing, it should be treated as an error, and if you treat it as an error, you now are "strict" by definition.
Any reasonably good C code I ever worked with aimed to be warning free. But yes, if you can also make it an error. The flexibility is important though.
Regardless of whether you're "aiming for the code to be warning free" or telling the compiler to turn the warning into an error, you will make the implicit cast explicit and move on with your day. You've already said you should use your tools to flag these errors and that aiming to be warning free is a good thing, so I don't understand where we disagree, especially when making implicit casts explicit costs a single-digit number of keystrokes.