logoalt Hacker News

david2ndaccount • today at 6:51 AM • 1 reply • view on HN

I was unclear in the article, but in my defense I wrote it in a hurry on the couch after seeing the convoluted backwards loop an llm had extruded. I meant if you are actually doing something with the index variable other than indexing. Mixing signed and unsigned types, possibly of different sizes, has surprising behavior to many programmers who don’t have the “usual arithmetic conversions” memorized. If you’re working in size_t the result simplifies: everything becomes size_t. And you generally have size_t anyway as you’re using the result of sizeof or an allocation size passed to your allocation function.

In general I want to avoid signed types for counts and sizes as then you have to consider both boundary conditions which is easy to mess up.


Replies

uecker • today at 7:03 AM

I agree that mixing signed and unsigned types creates friction. After trying to use unsigned for sizes and indices for a while, I changed my mind and now use signed types almost everywhere, except for modulo arithmetic and bit masks, and I found this removes all problems I had before.

I don't think the usual arithmetic conversions are very problematic, IMHO there is a lot of FUD about this. The rule is also very simple: "Operands are converted to the higher ranked type but at least to the rank of int, and to the signed type if it covers all values of both types and otherwise to the unsigned version." This is the complete rule.

I like the your final version, but it is a bit too clever for my taste.