[PATCH v9 13/14] include/array_length.h: add array_foreach[_const] macros
Adhemerval Zanella Netto
adhemerval.zanella@linaro.org
Mon Jun 16 18:01:17 GMT 2025
On 16/06/25 14:56, Florian Weimer wrote:
> * Adhemerval Zanella Netto:
>
>> On 11/06/25 22:35, H. Peter Anvin wrote:
>>> Add simple-to-use iterator macros for arrays. They are used instead
>>> of explicit for statements, like:
>>>
>>> /* Test all common speeds */
>>> array_foreach_const (ts, test_speeds)
>>> test (fd, *ts);
>>>
>>> In this case, ts will be a const pointer to each of the elements of
>>> test_speeds in turn.
>>>
>>> Named array_foreach*() to allow for other kinds of equivalent iterator
>>> macros in the future.
>>>
>>> Signed-off-by: "H. Peter Anvin" (Intel) <hpa@zytor.com>
>>
>> LGTM, thanks.
>>
>> Reviewed-by: Adhemerval Zanella <adhemerval.zanella@linaro.org>
>>
>>> ---
>>> include/array_length.h | 14 ++++++++++++++
>>> 1 file changed, 14 insertions(+)
>>>
>>> diff --git a/include/array_length.h b/include/array_length.h
>>> index 2305e211b210..53e436b53387 100644
>>> --- a/include/array_length.h
>>> +++ b/include/array_length.h
>>> @@ -33,4 +33,18 @@
>>> VAR must evaluate to an array, not a pointer. */
>>> #define array_end(var) (&(var)[array_length (var)])
>>>
>>> +/* array_foreach (PTR, ARRAY) iterates over all the elements in an
>>> + array, assigning the locally defined pointer variable PTR to each
>>> + element in turn.
>>> +
>>> + array_foreach_const (PTR, ARRAY) does the same, but PTR is declared
>>> + const even if the array is not. */
>
> Note that PTR is not a variable, but an identifier. The comment does
> not make this quite clear. And PTR is not declared const, it's declared
> as a pointer *to* const.
>
> I wasn't sure if I like these macros, but I think they are not too bad,
> given that the way they work, the loop body is not covered by the macro,
> and break, continue, return all keep working as expected.
>
>>> +#define array_foreach(ptr, array) \
>>> + for (__typeof ((array)[0]) *ptr = (array) ; \
>>> + ptr < array_end(array) ; ptr++)
>>> +
>>> +#define array_foreach_const(ptr, array) \
>>> + for (const __typeof ((array)[0]) *ptr = (array) ; \
>>> + ptr < array_end(array) ; ptr++)
>>> +
>>> #endif /* _ARRAY_LENGTH_H */
>
> Please fix the style nits (missing spaces before '(') before committing.
Ack, I have updated my branch with these fixes.
>
> Thanks,
> Florian
>
More information about the Libc-alpha
mailing list