Re: [PATCH v2] <sys/param.h>: Add nitems() and snitems() macros

From: Jonathan Wakely
Date: Fri Sep 25 2020 - 13:40:01 EST


On 25/09/20 18:30 +0200, Alejandro Colomar via Libstdc++ wrote:
Hello Jonathan,

On 2020-09-25 16:48, Jonathan Wakely wrote:
Do you really need to provide snitems?

Users can use (ptrdiff_t)nitems if needed, can't they?

They can, but that adds casts in the code,
which makes longer lines that are somewhat harder to read.
To avoid that, users may sometimes omit the cast with possible UB.
BTW, I use

IMO, array indices should be declared as 'ptrdiff_t' always,
and not 'size_t'. More generically, I use unsigned integer types for two
reasons: bitwise operations, and library functions that require me to do so.

I don't intend to force anyone with my opinion, of course,
but if I were to choose a type for 'nitems()', it would be 'ptrdiff_t'.

However, for legacy reasons people will expect that macro to be unsigned,
so I'd have 'nitems()' unsigned, and then a signed version prefixed with an 's'.

Some very interesting links about this topic:

Bjarne Stroustrup (and others) about signed and unsigned integers:
https://www.youtube.com/watch?v=Puio5dly9N8&t=12m56s
https://www.youtube.com/watch?v=Puio5dly9N8&t=42m41s

The two links above are two interesting moments of the same video.

I guess that might be the reason they added std::ssize, BTW.

Yes, I'm aware of all the rationale. I already said that it makes
sense in C++ where you have generic code. I am not convinced that it's
necessary to add to <sys/param.h> when all it does is a cast from
size_t to ptrdiff_t.