]> git.ipfire.org Git - thirdparty/glibc.git/commitdiff
include/array_length.h: add array_foreach[_const] macros
authorH. Peter Anvin <hpa@zytor.com>
Thu, 12 Jun 2025 01:35:44 +0000 (18:35 -0700)
committerAdhemerval Zanella <adhemerval.zanella@linaro.org>
Tue, 17 Jun 2025 12:57:40 +0000 (09:57 -0300)
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>
Reviewed-by: Adhemerval Zanella <adhemerval.zanella@linaro.org>
include/array_length.h

index 2305e211b2109a823cc4dca17cbdc012ee05032f..2a4f09fd371301c5dde74538cd6d5bd085ecfd38 100644 (file)
    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. */
+#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 */