logoalt Hacker News

r1chardnlyesterday at 9:43 AM1 replyview on HN

From one of his other blogposts. "Guidelines for computing sizes and subscripts"

  Never mix unsigned and signed operands. Prefer signed. If you need to convert an operand, see (2).
https://nullprogram.com/blog/2024/05/24/

https://www.youtube.com/watch?v=wvtFGa6XJDU


Replies

poly2ityesterday at 10:51 AM

I still don't understand how these arguments make sense for new code. Naturally, sizes should be unsigned because they represent values which cannot be unsigned. If you do pointer/size arithmetic, the only solution to avoid overflows is to overflow-check and range-check before computation.

You cannot even check the signedness of a signed size to detect an overflow, because signed overflow is undefined!

The remaining argument from what I can tell is that comparisons between signed and unsigned sizes are bug-prone. There is however, a dedicated warning to resolve this instantly.

It makes sense that you should be able to assign a pointer to a size. If the size is signed, this cannot be done due to its smaller capacity.

Given this, I can't understand the justification. I'm currently using unsigned sizes. If you have anything contradicting, please comment :^)

show 7 replies